2014-02-05 16:33:10 -06:00
|
|
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
|
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
// except according to those terms.
|
|
|
|
|
2013-10-28 17:22:49 -05:00
|
|
|
/* Any copyright is dedicated to the Public Domain.
|
|
|
|
* http://creativecommons.org/publicdomain/zero/1.0/ */
|
|
|
|
|
2014-11-26 07:12:18 -06:00
|
|
|
fn call_it<F>(f: F)
|
|
|
|
where F : FnOnce(String) -> String
|
|
|
|
{
|
2014-05-25 05:17:19 -05:00
|
|
|
println!("{}", f("Fred".to_string()))
|
2013-10-28 17:22:49 -05:00
|
|
|
}
|
|
|
|
|
2015-01-02 16:32:54 -06:00
|
|
|
fn call_a_thunk<F>(f: F) where F: FnOnce() {
|
2013-10-29 17:06:13 -05:00
|
|
|
f();
|
|
|
|
}
|
|
|
|
|
2015-01-02 16:32:54 -06:00
|
|
|
fn call_this<F>(f: F) where F: FnOnce(&str) + Send {
|
2013-10-29 17:06:13 -05:00
|
|
|
f("Hello!");
|
|
|
|
}
|
|
|
|
|
|
|
|
fn call_bare(f: fn(&str)) {
|
|
|
|
f("Hello world!")
|
|
|
|
}
|
|
|
|
|
|
|
|
fn call_bare_again(f: extern "Rust" fn(&str)) {
|
|
|
|
f("Goodbye world!")
|
|
|
|
}
|
|
|
|
|
2013-10-28 17:22:49 -05:00
|
|
|
pub fn main() {
|
2013-10-29 17:06:13 -05:00
|
|
|
// Procs
|
|
|
|
|
2014-05-25 05:17:19 -05:00
|
|
|
let greeting = "Hello ".to_string();
|
2014-11-26 07:12:18 -06:00
|
|
|
call_it(|s| {
|
2014-05-27 22:44:58 -05:00
|
|
|
format!("{}{}", greeting, s)
|
2013-10-28 17:22:49 -05:00
|
|
|
});
|
|
|
|
|
2014-05-25 05:17:19 -05:00
|
|
|
let greeting = "Goodbye ".to_string();
|
2014-11-26 07:12:18 -06:00
|
|
|
call_it(|s| format!("{}{}", greeting, s));
|
2013-10-28 17:22:49 -05:00
|
|
|
|
2014-05-25 05:17:19 -05:00
|
|
|
let greeting = "How's life, ".to_string();
|
2014-11-26 07:12:18 -06:00
|
|
|
call_it(|s: String| -> String {
|
2014-05-27 22:44:58 -05:00
|
|
|
format!("{}{}", greeting, s)
|
2013-10-28 17:22:49 -05:00
|
|
|
});
|
2013-10-29 17:06:13 -05:00
|
|
|
|
|
|
|
// Closures
|
|
|
|
|
2014-01-09 04:06:55 -06:00
|
|
|
call_a_thunk(|| println!("Hello world!"));
|
2013-10-29 17:06:13 -05:00
|
|
|
|
2014-01-09 04:06:55 -06:00
|
|
|
call_this(|s| println!("{}", s));
|
2013-10-29 17:06:13 -05:00
|
|
|
|
|
|
|
// External functions
|
|
|
|
|
2015-04-10 13:12:43 -05:00
|
|
|
fn foo(s: &str) {}
|
|
|
|
call_bare(foo);
|
2013-10-29 17:06:13 -05:00
|
|
|
|
2015-04-10 13:12:43 -05:00
|
|
|
call_bare_again(foo);
|
2013-10-28 17:22:49 -05:00
|
|
|
}
|