Skip to content

Instantly share code, notes, and snippets.

@rcook
Created March 3, 2019 17:34
Show Gist options
  • Select an option

  • Save rcook/180e2fb5dbde952be777dbc813272b18 to your computer and use it in GitHub Desktop.

Select an option

Save rcook/180e2fb5dbde952be777dbc813272b18 to your computer and use it in GitHub Desktop.
Use of as_ref() in Rust
struct Foo {
title: String,
}
impl Foo {
fn new(title: &str) -> Foo {
Foo {
title: title.to_string(),
}
}
}
fn do_something(opt_foo: &Option<Foo>) -> () {
println!(
"f.title={}",
opt_foo
.as_ref()
.map_or(
"(none)".to_string(),
|ref foo| foo.title.clone()))
}
fn main() {
do_something(&Some(Foo::new("<title>")))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment