Browse Source

structs (and tuple structs, and also newtypes)

a tuple struct is basically a named tuple.  as a struct it has a name
and as a tuple it doesn't have field names.

tuple structs with only one field are also called newtypes (or said to
be using the newtype pattern).  they are useful for wrapping values to
be able to differentiate them from other values with the same field
type.
Lucas Stadler 10 years ago
parent
commit
f4475010e5
1 changed files with 14 additions and 0 deletions
  1. 14 0
      rust/book/src/main.rs

+ 14 - 0
rust/book/src/main.rs

@ -20,6 +20,13 @@ fn inc(x: i32) -> i32 {
20 20
    x + 1
21 21
}
22 22
23
struct Point {
24
    x: i32,
25
    y: i32
26
}
27
28
struct Meters(i32);
29
23 30
fn main() {
24 31
    let x = 5; // x: i32
25 32
@ -47,4 +54,11 @@ fn main() {
47 54
    } else {
48 55
        println!("The universe is basically ok.");
49 56
    }
57
58
    // structs
59
    let p = Point{x: 1, y: 2};
60
    println!("Meet you at ({}, {}).", p.x, p.y);
61
62
    let Meters(l) = Meters(3);
63
    println!("It's {}m until there, too long for me. Bye.", l)
50 64
}