Rustの関連関数
public.icon
::newの行にある::構文はnewがString型の関連関数であることを示しています
&selfなし。
code:rust
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// 関連関数(selfなし)- コンストラクタ的な用途
fn new(width: u32, height: u32) -> Self {
Rectangle { width, height }
}
fn square(size: u32) -> Self {
Rectangle { width: size, height: size }
}
// メソッド(&selfあり)
fn area(&self) -> u32 {
self.width * self.height
}
}
// 呼び出し
let rect = Rectangle::new(30, 50); // 関連関数は :: で呼ぶ
let sq = Rectangle::square(10);
let a = rect.area(); // メソッドは . で呼ぶ