rust
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| rust [2024/07/11 20:12] – [Control flow] utedass | rust [2024/07/11 20:46] (current) – [Matching] utedass | ||
|---|---|---|---|
| Line 171: | Line 171: | ||
| dbg!(& | dbg!(& | ||
| } | } | ||
| + | </ | ||
| + | |||
| + | ==== Enums ==== | ||
| + | <code rust> | ||
| + | enum IpAddrKind { | ||
| + | V4, | ||
| + | V6, | ||
| + | } | ||
| + | |||
| + | fn main() { | ||
| + | let four = IpAddrKind:: | ||
| + | let six: IpAddrKind = IpAddrKind:: | ||
| + | } | ||
| + | </ | ||
| + | Enums can have different content for their different enumerations. | ||
| + | <code rust> | ||
| + | enum Message { | ||
| + | Quit, | ||
| + | Move { x: i32, y: i32 }, | ||
| + | Write(String), | ||
| + | ChangeColor(i32, | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | They can also have functions | ||
| + | <code rust> | ||
| + | enum Message { | ||
| + | Quit, | ||
| + | Move { x: i32, y: i32 }, | ||
| + | Write(String), | ||
| + | ChangeColor(i32, | ||
| + | } | ||
| + | |||
| + | impl Message { | ||
| + | fn call(& | ||
| + | // method body would be defined here | ||
| + | } | ||
| + | } | ||
| + | |||
| + | let m = Message:: | ||
| + | m.call(); | ||
| + | </ | ||
| + | |||
| + | There is the special Option type available in the standard library std:: | ||
| + | <code rust> | ||
| + | enum Option< | ||
| + | None, | ||
| + | Some(T), | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | <code rust> | ||
| + | let some_number = Some(5); | ||
| + | let some_char = Some(' | ||
| + | |||
| + | let absent_number: | ||
| + | </ | ||
| + | |||
| + | ==== Matching ==== | ||
| + | <code rust> | ||
| + | enum UsState { | ||
| + | Alabama, | ||
| + | Alaska, | ||
| + | // --snip-- | ||
| + | } | ||
| + | |||
| + | enum Coin { | ||
| + | Penny, | ||
| + | Nickel, | ||
| + | Dime, | ||
| + | Quarter(UsState), | ||
| + | } | ||
| + | |||
| + | fn value_in_cents(coin: | ||
| + | match coin { | ||
| + | Coin::Penny => 1, | ||
| + | Coin:: | ||
| + | Coin::Dime => 10, | ||
| + | Coin:: | ||
| + | println!(" | ||
| + | 25 | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | Can match integers as well | ||
| + | <code rust> | ||
| + | let dice_roll = 9; | ||
| + | match dice_roll { | ||
| + | 3 => add_fancy_hat(), | ||
| + | 7 => remove_fancy_hat(), | ||
| + | other => move_player(other), | ||
| + | } | ||
| + | |||
| + | fn add_fancy_hat() {} | ||
| + | fn remove_fancy_hat() {} | ||
| + | fn move_player(num_spaces: | ||
| </ | </ | ||
rust.1720728721.txt.gz · Last modified: 2024/07/11 20:12 by utedass
