标签:count 一个 结构 函数 rectangle python rect class 多个
struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
这样可以定义一个结构体。
当已有一个结构体User1时:
let user2 = User {
email: String::from("another@example.com"),
username: String::from("anotherusername567"),
..user1
};
可以这样把剩余的字段赋值为和user1相同的值。
struct Point(i32, i32, i32); let origin = Point(0, 0, 0);
这样便定义了一个元组结构体,在你希望命名一个元组时很有用。
结构体内可以实现方法:
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
这样调用:
let rect1 = Rectangle { width: 30, height: 50 };
rect1.area();
一个impl内可以实现若干方法,一个结构体也可以有多个impl。
impl Rectangle {
fn square(size: u32) -> Rectangle {
Rectangle { width: size, height: size }
}
}
这样调用关联函数:
let sq = Rectangle::square(3);
标签:count 一个 结构 函数 rectangle python rect class 多个
原文地址:https://www.cnblogs.com/kwebi/p/9415355.html