structAnimal{ name:String, }traitDog{fnbark(&self);// bark() says it needs a &self and returns nothingfnrun(&self);// run() says it needs a &self and returns nothing.// So now we have to write them ourselves.}i
takes no input and returns nothing. F: FnOnce() { // ^ TODO: Try changing this to `Fn` or `FnMut`. f();}// A function which takes a closure and returns an `i32`.fn apply_to_3<F>(f: F) -> i32 where // The closure takes an `i32` and returns an `i32`....
// `F` must implement `Fn` for a closure which takes no// inputs and returns nothing - exactly what is required// for `print`.fn apply<F>(f: F) where F: Fn() { f();}fn main() { let x = 7; // Capture `x` into an anonymous type and implement // `Fn`...
首先,在第3行修改了main()函数,使用-> Result((), std::io::Error>返回一个Result。 记住,()是单元类型,是另一种表达无(nothing)的方式。可以把这种返回值(-> Result<(),...>)读作“不返回任何内容,但有可能失败”(Returns nothing, but may fail)。
//returnvalue into thefunction // that calls it letsome_string = String::from("yours"); // some_string comes into scope some_string // some_string is returned and // moves out to the calling //function } // Thisfunctiontakes a String and returns it ...
s2 was moved, so nothing // happens. s1 goes out of scope and is dropped. fn gives_ownership() -> String { // gives_ownership will move its // return value into the function // that calls it let some_string = String::from("yours"); // some_string comes into scope some_...
functions of a given type (equiv to static methods in OOP)// String::new() creates an empty string of type String (growable UTF-8 encoded text)let mut guess = String::new();/*std::io::stdin, if you don't use the import at the top of filestd::io::stdin() returns an insta...
// Some async function, e.g. polling a URL with [https://docs.rs/reqwest]// Remember, Rust functions do nothing until you .await them, so this isn't// actually making a HTTP request yet.letasync_fn=reqwest::get("http://adamchalmers.com");// Wrap the async function in my hypothe...
// return value into the function // that calls it let some_string = String::from("yours"); // some_string comes into scope some_string // some_string is returned and // moves out to the calling // function } // This function takes a String and returns it ...
letv:Vec<i32>=Vec::new();// v is first moved into print_len's v1// and then moved into v2 when print_len returns itletv2=print_len(v);fnprint_len(v1:Vec<i32>)->Vec<i32>{println!("v1's length is{}",v1.len());v1// v1 is moved out of the function} ...