Skip to content

Instantly share code, notes, and snippets.

@zesterer
Last active August 15, 2018 10:42
Show Gist options
  • Save zesterer/0098034d3f15ce13d1b6c5a811bc41aa to your computer and use it in GitHub Desktop.
Save zesterer/0098034d3f15ce13d1b6c5a811bc41aa to your computer and use it in GitHub Desktop.
Return a borrowed trait object by reference from a method in Rust
trait Volume {}
struct RawChunk; impl Volume for RawChunk {}
struct RleChunk; impl Volume for RleChunk {}
struct FileChunk; impl Volume for FileChunk {}
struct Container {
raw: Option<RawChunk>,
rle: Option<RleChunk>,
file: Option<FileChunk>,
}
impl Container {
fn get<'a>(&'a self, variant: i32) -> Option<&'a dyn Volume> {
match variant {
0 => self.raw.as_ref().map(|c| c as &dyn Volume),
1 => self.rle.as_ref().map(|c| c as &dyn Volume),
2 => self.file.as_ref().map(|c| c as &dyn Volume),
_ => panic!(),
}
}
}
fn main() {
println!("Hello, world!");
let container = Container {
raw: Some(RawChunk),
rle: Some(RleChunk),
file: Some(FileChunk),
};
let _ = container.get(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment