generated at
Rustのstruct




特徴
メソッドを生やせる

命名
構造体名はCamelCase
フィールド名はsneak_case


種類
名前付きフィールド構造体
個々の要素に名前を与える
rs
struct GrayscaleMap { pixels: Vec<u8>, size: (usize, usize), }
タプル構造体
順番で構成要素を指定する
rs
struct Bounds(usize, usize)
ユニット構造体
要素なし
rs
struct UniqueValue;

初期化

update
functional record update syntax



implでメソッドを生やす
メソッドの第一引数は self
この型は自明なので、基本省略する
self: Hoge -省略→ self
self: &Hoge -省略→ &self
self: &mut Hoge -省略→ &mut self
rs
impl VendingMachine { // static method. `self`を引数に取らない fn new() -> Self { VendingMachine { drinks: Vec::new(), cash_balance: 0, } } // 通常のmethod. 第一引数は`self` fn add_drink(&mut self, drink: Drink) { self.drinks.push(drink); } }

genericsを用いた構造体
rs
struct Queue<T> { older: Vec<T>, younger: Vec<T>, }


生存期間パラメータを持たせる
rs
struct Exrema<'elt> { greatest: &'elt i32, least: &'elt i32, }