Last active
July 20, 2020 01:29
-
-
Save webern/c013a524f5ac436538839f751e81e038 to your computer and use it in GitHub Desktop.
Rust struct where user decides who owns the data.
This file contains 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
#![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