Przeglądaj źródła

add pointer examples.

Lucas Stadler 11 lat temu
rodzic
commit
e0296ef20c
1 zmienionych plików z 86 dodań i 0 usunięć
  1. 86 0
      rust/pointers.rs

+ 86 - 0
rust/pointers.rs

@ -0,0 +1,86 @@
1
extern crate debug;
2
3
mod wrapped {
4
    fn get_wrapped(v: &int) -> int {
5
        *v
6
    }
7
8
    #[deriving(Show)]
9
    struct Point {x: f64, y: f64}
10
11
    fn get_wrapped_struct(p: &Point) -> Point {
12
        *p
13
    }
14
15
    pub fn run() {
16
        println!("\nwrapped:");
17
18
        // mhh... i thought this would "move" the ownership, but somehow it doesn't. because it's immutable?
19
        // by the way, how is immutability defined? we can have mutable variables, but also mutable pointers,
20
        // what does that mean?
21
        println!("get_wrapped(&1) = {}", get_wrapped(&1));
22
23
        // even this does work, so what doesn't?
24
        let point = Point{x: 3.1, y: 4.7};
25
        println!("get_wrapped_struct(&Point{{x = 3.1, y = 4.7}}) = {}", get_wrapped_struct(&point));
26
    }
27
}
28
29
mod list_with_box {
30
    #[deriving(Show)]
31
    pub enum List<A> {
32
        Nil,
33
        Cons(A, Box<List<A>>)
34
    }
35
36
    // this could already be "ok", if we accept that the argument will be copied just to match on it. i think rust uses `memcpy` for that, so it should be quite fast, even if generally "bad".
37
    pub fn cons<A>(x: A, xs: List<A>) -> List<A> {
38
        match xs {
39
            Nil => Cons(x, box Nil),
40
            _   => Cons(x, box xs)
41
        }
42
    }
43
44
    pub fn run() {
45
        println!("\nlist_with_box:");
46
47
        let l: List<int> = cons(1, cons(2, Nil));
48
49
        println!("l = {}", l);
50
        println!("cons(3, box l) = {:?}", cons(3, l));
51
    }
52
}
53
54
mod list_with_ref {
55
    #[deriving(Show)]
56
    pub enum List<'a, A: 'a> {
57
        Nil,
58
        Cons(A, &'a List<'a A>) // are there alternatives to boxing? (i think not -- Rc, Arc, etc. *are* boxes. right?)
59
    }
60
61
    // we want to pass a reference to the list, pattern match on it and then return a new list that references the old one.
62
    pub fn cons<'a, A>(x: A, xs: &'a List<A>) -> List<'a, A> {
63
        match *xs {
64
            Nil => Cons(x, xs),
65
            ref xs  => Cons(x, xs)
66
        }
67
    }
68
69
    pub fn run() {
70
        println!("\nlist_with_ref:");
71
72
        //let l: &List<int> = &Cons(1, &Cons(2, &Cons(3, &Nil)));
73
        let nil = &Nil;
74
        let l: &List<int> = &cons(1, nil);
75
76
        println!("l = {:?}", l);
77
        println!("lwr_cons_with_ref(1, l) = {:?}", cons(1, l));
78
    }
79
}
80
81
pub fn main() {
82
    wrapped::run();
83
84
    list_with_box::run();
85
    list_with_ref::run();
86
}