Closures

  fn main() {
      // Increment via closures and functions.
      fn function(i: i32) -> i32 {
          i + 1
      }

      // Closures are anonymous, here we are binding them to references
      // Annotation is identical to function annotation but is optional
      // as are the `{}` wrapping the body. These nameless functions
      // are assigned to appropriately named variables.
      let closure_annotated = |i: i32| -> i32 { i + 1 };
      let closure_inferred = |i| i + 1;

      let i = 1;
      // Call the function and closures.
      println!("function: {}", function(i));
      println!("closure_annotated: {}", closure_annotated(i));
      println!("closure_inferred: {}", closure_inferred(i));

      // A closure taking no arguments which returns an `i32`.
      // The return type is inferred.
      let one = || 1;
      println!("closure returning one: {}", one());
  }
function: 2
closure_annotated: 2
closure_inferred: 2
closure returning one: 1
//rectangle.translate(1.0, 0.0); // TODO ^ Try uncommenting this line // Okay! Mutable objects can call mutable methods square.translate(1.0, 1.0); let pair = Pair(Box::new(1), Box::new(2)); pair.destroy(); // Error! Previous `destroy` call "consumed" `pair` //pair.destroy(); // TODO ^ Try uncommenting this line }
Rectangle perimeter: 14
Rectangle area: 12
Destroying Pair(1, 2)