Skip to content

Instantly share code, notes, and snippets.

@krisselden
Created September 19, 2019 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krisselden/f867dbadb51c9252658d03f594087648 to your computer and use it in GitHub Desktop.
Save krisselden/f867dbadb51c9252658d03f594087648 to your computer and use it in GitHub Desktop.
#[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