Created
September 19, 2019 18:12
-
-
Save krisselden/f867dbadb51c9252658d03f594087648 to your computer and use it in GitHub Desktop.
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
#[derive(Debug, Clone, Copy)] | |
enum MyRef<'a> { | |
String(&'a str), | |
Bytes(&'a [u8]), | |
} | |
impl<'a> Into<&'a str> for MyRef<'a> { | |
fn into(self) -> &'a str { | |
if let MyRef::String(s) = self { | |
s | |
} else { | |
panic!("not a str") | |
} | |
} | |
} | |
impl<'a> Into<&'a [u8]> for MyRef<'a> { | |
fn into(self) -> &'a [u8] { | |
if let MyRef::Bytes(b) = self { | |
b | |
} else { | |
panic!("not a bytes") | |
} | |
} | |
} | |
fn main() { | |
let mut owned = String::new(); | |
owned.push_str("Hello"); | |
owned.push_str(" World"); | |
owned.push('!'); | |
let strref: &str = &owned; | |
let bytes = owned.as_bytes(); | |
let items = vec![ | |
MyRef::String(strref), | |
MyRef::Bytes(bytes), | |
]; | |
println!("{:?}", items); | |
let bytescopy: &[u8] = items[1].into(); | |
let strcopy: &str = items[0].into(); | |
// copy just copies the memory of the structure | |
// the bytes and str are not actually copied, just their pointers | |
println!("{:p} == {:p}", strref, strcopy); | |
println!("{:p} == {:p}", bytes, bytescopy); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment