問題一覧に戻る
中級構造体
問題50: 関連関数
関連関数は構造体に属するがselfパラメータを持たない関数で、主にコンストラクタとして使われます。Self型は実装している型自身を指し、返り値や型名として使えます。new、from、defaultなどの命名で、目的に応じたコンストラクタを複数定義できます。Rustの慃習的なインスタンス作成方法です。
struct Point {
x: f64,
y: f64,
}
impl Point {
// コンストラクタ
fn new(x: f64, y: f64) -> {
{ x, y }
}
// デフォルトコンストラクタ
fn origin() -> {
Self::(0.0, 0.0)
}
// タプルから作成
fn from_tuple(tuple: (f64, f64)) -> Self {
Self {
x: tuple.,
y: tuple.,
}
}
}
fn main() {
let p1 = ::new(3.0, 4.0);
let p2 = Point::();
let p3 = Point::from_tuple((5.0, 6.0));
println!("P1: ({}, {})", p1.x, p1.y);
println!("P2: ({}, {})", p2.x, p2.y);
println!("P3: ({}, {})", p3.x, p3.y);
}