coredump-ch / intro-to-rust

Intro-presentation about Rust.
Creative Commons Attribution 4.0 International
11 stars 4 forks source link

Introduce closures #15

Open dbrgn opened 8 years ago

dns2utf8 commented 8 years ago

Maybe add a slide along these lines:

let mut data = 42;
let borrowing = || {
  data + 1;
  println!("borrowing: {}", data);
}
let moves = move || {
  data + 1;
  println!("move: {}", data);
}

// process(borrowing); // <-- enable just one of them
// process(moves);   // <-- enable just one of them
println!("main: {}", data);
rnestler commented 8 years ago

let move = move won't work, because move is a keyword isn't it?

dbrgn commented 8 years ago

Is move something you specify at definition? I thought that's a keyword you use at invocation...

I'd just show a simple example along these lines:

fn addone(n: u8): u8 {
  return n + 1;
}

equals

let addone = |n: u8| n + 1;
dns2utf8 commented 8 years ago

move is a keyword :stuck_out_tongue_closed_eyes: http://doc.rust-lang.org/grammar.html#keywords

I am not sure if you can cast the closure to the same signature:

expected `()`,
    found `[closure@src/main.rs:2:16: 2:29]`  

vs.

expected `()`,
    found `fn(u8) -> u8 {addoneFn}` 

compiler errors with this code:

fn main() {
  let addone = |n: u8| n + 1;

  //() = addone
  () = addoneFn
}
fn addoneFn(n: u8) -> u8 {
  return n + 1;
}
dns2utf8 commented 8 years ago

I extended the example, but it is not working yet: https://play.rust-lang.org/?gist=990468aeaef7ffc5b188e81d3a440e5b&version=beta

dbrgn commented 8 years ago

Of course it's not the same signature inside the compiler. One of them is a closure, the other is a function.

Yes, I know that it's a keyword. But as far as I know, move is not part of a closure signature. So it's used to invoke a closure, not to define a closure.