]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass/closure-reform.rs
auto merge of #13600 : brandonw/rust/master, r=brson
[rust.git] / src / test / run-pass / closure-reform.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 /* Any copyright is dedicated to the Public Domain.
12  * http://creativecommons.org/publicdomain/zero/1.0/ */
13
14 use std::cast;
15 use std::io::stdio::println;
16
17 fn call_it(f: proc(~str) -> ~str) {
18     println!("{}", f(~"Fred"))
19 }
20
21 fn call_a_thunk(f: ||) {
22     f();
23 }
24
25 fn call_this(f: |&str|:Send) {
26     f("Hello!");
27 }
28
29 fn call_that(f: <'a>|&'a int, &'a int|: -> int) {
30     let (ten, forty_two) = (10, 42);
31     println!("Your lucky number is {}", f(&ten, &forty_two));
32 }
33
34 fn call_cramped(f:||->uint,g:<'a>||->&'a uint) {
35     let number = f();
36     let other_number = *g();
37     println!("Ticket {} wins an all-expenses-paid trip to Mountain View", number + other_number);
38 }
39
40 fn call_bare(f: fn(&str)) {
41     f("Hello world!")
42 }
43
44 fn call_bare_again(f: extern "Rust" fn(&str)) {
45     f("Goodbye world!")
46 }
47
48 pub fn main() {
49     // Procs
50
51     let greeting = ~"Hello ";
52     call_it(proc(s) {
53         greeting + s
54     });
55
56     let greeting = ~"Goodbye ";
57     call_it(proc(s) greeting + s);
58
59     let greeting = ~"How's life, ";
60     call_it(proc(s: ~str) -> ~str {
61         greeting + s
62     });
63
64     // Closures
65
66     call_a_thunk(|| println!("Hello world!"));
67
68     call_this(|s| println!("{}", s));
69
70     call_that(|x, y| *x + *y);
71
72     let z = 100;
73     call_that(|x, y| *x + *y - z);
74
75     call_cramped(|| 1, || unsafe {
76         static a: uint = 100;
77         cast::transmute(&a)
78     });
79
80     // External functions
81
82     call_bare(println);
83
84     call_bare_again(println);
85 }
86