3.2 構造
- 錆びに階級はない
構造体
- 複数のデータを含む型
- それぞれのデータを
field
属性と呼びます - プロパティにアクセスするには
.
#[derive(Debug)]
struct Rectangle {
width: i32,
height: i32,
}
fn main() {
let rect = Rectangle {
width: 5,
height: 10,
};
println!("{}", rect.width);
println!("{:#?}", rect);
}
構造体メソッド
- 相関関数
- インスタンスメソッド
- コンストラクタ
- 自己
例1
#[derive(Debug)]
struct Rectangle {
width: i32,
height: i32,
}
impl Rectangle {
// 关联函数
fn area(width: i32, height: i32) -> i32 {
width * height
}
// 实例方法
fn cal(&self) -> i32 {
self.width * self.height
}
// 构造函数
fn new(width: i32, height: i32) -> Self {
Rectangle {
width, height }
}
}
fn main() {
let rect = Rectangle {
width: 5,
height: 10,
};
let num1 = Rectangle::area(5, 5);
println!("{}", num1);
println!("{}", rect.cal());
let rect2 = Rectangle::new(5, 5);
println!("{:#?}", rect2);
}
例 2
#[derive(Debug)]
struct Person {
name: String,
age: i32,
}
impl Person {
// 可能在外部调用,使用pub关键字
pub fn new(name: String, age: i32) -> Self {
Person {
name, age }
}
}
fn main() {
let person1 = Person::new("Star-tears".to_string(), 18);
println!("{:#?}", person1);
}
- &自己
- 自分自身(&M)
- 自己
- ミュートセルフ
例 3
#[derive(Debug)]
struct Person {
name: String,
age: i32,
}
impl Person {
// 可能在外部调用,使用pub关键字
pub fn new(name: String, age: i32) -> Self {
Person {
name, age }
}
fn greet(&self) -> String {
format!("Hi {}", self.name)
}
fn add_age(&mut self, n: i32) {
self.age += n;
}
}
fn main() {
let mut person1 = Person::new("Star-tears".to_string(), 18);
println!("{:#?}", person1);
println!("{}", person1.greet());
person1.add_age(3);
println!("{}", person1.age);
}
&
参照ですがデフォルトでは不変です、可変にしたい場合はmut
キーワードを追加する必要があります