User Tools

Site Tools


rust

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
rust [2024/07/11 20:28] – [Debug attribute and println!] utedassrust [2024/07/11 20:46] (current) – [Matching] utedass
Line 175: Line 175:
 ==== Enums ==== ==== Enums ====
 <code rust> <code rust>
 +enum IpAddrKind {
 +    V4,
 +    V6,
 +}
  
 +fn main() {
 +    let four = IpAddrKind::V4;
 +    let six: IpAddrKind = IpAddrKind::V6; // Explicit type
 +}
 </code> </code>
 Enums can have different content for their different enumerations. Enums can have different content for their different enumerations.
Line 204: Line 212:
     let m = Message::Write(String::from("hello"));     let m = Message::Write(String::from("hello"));
     m.call();     m.call();
 +</code>
 +
 +There is the special Option type available in the standard library std::option::Option
 +<code rust>
 +enum Option<T> {
 +    None,
 +    Some(T),
 +}
 +</code>
 +
 +<code rust>
 +let some_number = Some(5);
 +let some_char = Some('e');
 +
 +let absent_number: Option<i32> = None;
 +</code>
 +
 +==== Matching ====
 +<code rust>
 +enum UsState {
 +    Alabama,
 +    Alaska,
 +    // --snip--
 +}
 +
 +enum Coin {
 +    Penny,
 +    Nickel,
 +    Dime,
 +    Quarter(UsState),
 +}
 +
 +fn value_in_cents(coin: Coin) -> u8 {
 +    match coin {
 +        Coin::Penny => 1,
 +        Coin::Nickel => 5,
 +        Coin::Dime => 10,
 +        Coin::Quarter(state) => {
 +            println!("State quarter from {:?}!", state);
 +            25
 +        }
 +    }
 +}
 +</code>
 +
 +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: u8) {}
 </code> </code>
rust.1720729696.txt.gz · Last modified: 2024/07/11 20:28 by utedass

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki