Created
May 29, 2019 07:14
-
-
Save pimeys/ec59d6dba1dc79f1374cb3f74ae42e66 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::borrow::Cow; | |
struct Container<'a> { | |
data: Option<Cow<'a, str>>, | |
} | |
impl<'a> Container<'a> { | |
pub fn new() -> Self { | |
Self { data: None } | |
} | |
// Interface allows anything that implement From<T> for Cow<'a, str> | |
pub fn add_data<S>(&mut self, data: S) | |
where | |
S: Into<Cow<'a, str>>, // Into is the counterpart for From | |
{ | |
self.data = Some(data.into()); | |
} | |
} | |
struct SomeResponse { | |
data: String, | |
} | |
fn main() { | |
let resp = SomeResponse { | |
data: String::from("allocated"), | |
}; | |
let mut c1 = Container::new(); | |
// We refer to resp.data. All good due to the lifetimes being compatible. | |
c1.add_data(&resp.data); | |
let mut c2 = Container::new(); | |
{ | |
let resp = SomeResponse { | |
data: String::from("allocated"), | |
}; | |
// Here we can't refer to data, our resp is dropped before c2 and the | |
// compiler would complain. By using the combination of From and Cow we | |
// can use the same interface for different kind of ownerships. | |
c2.add_data(resp.data); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment