Rustの列挙体
enum
2022/2/16 0:30:00
Rustの列挙体
matchを使う際、enum
に列挙子が残っていても、_
を使うと残りの処理を担わせることができる。_ => ()
と書けば、何もしないをできる。
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
fn main() {
let message = Message::Move{x:0, y:10};
match message {
Message::Move {x,y} => println!("Move(x:{},y:{})", x, y),
_ => (),
}
}
fn main() {
enum SpreadsheetCell {
Int(i32),
Float(f64),
Text(String),
}
let row = vec![
SpreadsheetCell::Int(3),
SpreadsheetCell::Text(String::from("blue")),
SpreadsheetCell::Float(10.12),
];
for r in &row {
match r {
SpreadsheetCell::Int(i) => println!("{}", i),
SpreadsheetCell::Text(s) => println!("{}", s),
SpreadsheetCell::Float(f) => println!("{}", f),
}
}
}
3
blue
10.12
https://doc.rust-jp.rs/book-ja/ch08-01-vectors.html#enumを使って複数の型を保持する
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
fn main() {
let message = Message::Move{x:0, y:10};
match message {
Message::Quit => println!("Quit"),
Message::Move {x,y} => println!("Move(x:{},y:{})", x, y),
Message::Write (s) => println!("Write({})", s),
Message::ChangeColor (r, g, b) => println!("ChangeColor({}, {}, {}", r, g, b),
}
}