Created
April 6, 2016 23:04
-
-
Save cfallin/29895380f3d8d2ff3f4d40d38d049d20 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::mem::transmute; | |
struct S1<'a> { | |
x: &'a u32, | |
} | |
struct S2<'a, 'b> { | |
x: &'a u32, | |
y: &'b u32, | |
} | |
trait S { | |
fn sum(&self) -> u32; | |
} | |
impl<'a> S for S1<'a> { | |
fn sum(&self) -> u32 { *self.x } | |
} | |
impl<'a, 'b> S for S2<'a, 'b> { | |
fn sum(&self) -> u32 { *self.x + *self.y } | |
} | |
struct Container<'a> { | |
ints: Vec<Box<u32>>, | |
structs: Vec<Box<S + 'a>>, | |
} | |
fn get_ref<'a, T>(x: &Box<T>) -> &'a T { | |
unsafe { transmute(&**x) } | |
} | |
fn make_container<'a>() -> Container<'a> { | |
let mut cont = Container { ints: Vec::new(), structs: Vec::new() }; | |
cont.ints.push(Box::new(1)); | |
cont.ints.push(Box::new(2)); | |
cont.ints.push(Box::new(3)); | |
let s1 = Box::new(S1 { x: get_ref(&cont.ints[0]) }); | |
let s2 = Box::new(S2 { x: get_ref(&cont.ints[1]), y: get_ref(&cont.ints[2]) }); | |
cont.structs.push(s1); | |
cont.structs.push(s2); | |
cont | |
} | |
fn main() { | |
let cont = make_container(); | |
for elem in cont.structs { | |
println!("{}", elem.sum()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment