Skip to content

Instantly share code, notes, and snippets.

@webern
Last active July 20, 2020 01:29
Show Gist options
  • Save webern/c013a524f5ac436538839f751e81e038 to your computer and use it in GitHub Desktop.
Save webern/c013a524f5ac436538839f751e81e038 to your computer and use it in GitHub Desktop.
Rust struct where user decides who owns the data.
#![forbid(missing_debug_implementations, missing_copy_implementations)]
#![deny(rust_2018_idioms)]
#![deny(clippy::pedantic)]
#![allow(dead_code)]
use std::borrow::Cow;
struct YouDecide<'a> {
s: Cow<'a, str>
}
impl<'a> YouDecide<'a> {
fn new<S: Into<Cow<'a, str>>>(value: S) -> Self {
Self{
s: value.into()
}
}
fn value(& self) -> &str {
self.s.as_ref()
}
}
fn main() {
let reference = "static";
let owned = String::from("owned");
let a = YouDecide::new(reference);
let b = YouDecide::new(owned.clone());
let c = YouDecide::new(&owned);
println!("{}", a.value());
println!("{}", b.value());
println!("{}", c.value());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment