|
| 1 | +// Copyright 2015 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 | + |
| 12 | +use std::mem; |
| 13 | + |
| 14 | +pub fn main() { |
| 15 | + // By Ref Capture |
| 16 | + let a = 10i32; |
| 17 | + let b = Some(|| println!("{}", a)); |
| 18 | + // When we capture by reference we can use any of the |
| 19 | + // captures as the discriminant since they're all |
| 20 | + // behind a pointer. |
| 21 | + assert_eq!(mem::size_of_val(&b), mem::size_of::<usize>()); |
| 22 | + |
| 23 | + // By Value Capture |
| 24 | + let a = Box::new(12i32); |
| 25 | + let b = Some(move || println!("{}", a)); |
| 26 | + // We captured `a` by value and since it's a `Box` we can use it |
| 27 | + // as the discriminant. |
| 28 | + assert_eq!(mem::size_of_val(&b), mem::size_of::<Box<i32>>()); |
| 29 | + |
| 30 | + // By Value Capture - Transitive case |
| 31 | + let a = "Hello".to_string(); // String -> Vec -> Unique -> NonZero |
| 32 | + let b = Some(move || println!("{}", a)); |
| 33 | + // We captured `a` by value and since down the chain it contains |
| 34 | + // a `NonZero` field, we can use it as the discriminant. |
| 35 | + assert_eq!(mem::size_of_val(&b), mem::size_of::<String>()); |
| 36 | + |
| 37 | + // By Value - No Optimization |
| 38 | + let a = 14i32; |
| 39 | + let b = Some(move || println!("{}", a)); |
| 40 | + // We captured `a` by value but we can't use it as the discriminant |
| 41 | + // thus we end up with an extra field for the discriminant |
| 42 | + assert_eq!(mem::size_of_val(&b), mem::size_of::<(i32, i32)>()); |
| 43 | +} |
0 commit comments