Last active
December 24, 2022 02:34
-
-
Save rinotc/bc5f97531e72ed35f38cfacd45de4d2f to your computer and use it in GitHub Desktop.
Rustの self, &self, &mut self に関するメモ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let mut rect = Rectangle { | |
width: 10, | |
height: 15, | |
}; | |
println!("rectangle area is: {}", rect.area()); | |
// let mut で宣言されたものでないと呼び出せない。 | |
rect.set_width(20); | |
// rect の内部状態が代わり、rect.widthが20になっているので、結果は300になる | |
println!("rectangle area is: {}", rect.area()); | |
// この段階でrectは使えなくなる。 | |
let triangle = rect.to_triangle(); | |
println!("triangle area is: {}", triangle.area()); | |
// rect.area() を参照しようとしてもコンパイルエラーになってしまう。 | |
// println!("rectangle area is: {}", rect.area()); | |
} | |
struct Rectangle { | |
width: u32, | |
height: u32, | |
} | |
impl Rectangle { | |
// 参照のみなので、不変な借用を使う | |
fn area(&self) -> u32 { | |
self.width * self.height | |
} | |
// 状態を変更するので、可変借用を使う | |
fn set_width(&mut self, w: u32) { | |
self.width = w; | |
} | |
// 所有権を渡してしまっているので、このメソッド呼び出し以降Rectangleは扱えなくなる | |
fn to_triangle(self) -> Triangle { | |
Triangle { | |
base: self.width, | |
height: self.height, | |
} | |
} | |
} | |
struct Triangle { | |
base: u32, | |
height: u32, | |
} | |
impl Triangle { | |
fn area(&self) -> u32 { | |
(self.base * self.height) / 2 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment