Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created June 7, 2020 14:31
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 rust-play/5bb57b8bf4bfc08758d9cb557e1fdbfe to your computer and use it in GitHub Desktop.
Save rust-play/5bb57b8bf4bfc08758d9cb557e1fdbfe to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::borrow::Cow;
// An user-defined enum
#[derive(Clone)]
enum Foo<'a, T> {
// Some fields that are not copy..
A(String),
B {
// Some other are..
a: usize,
// Some are generics..
b: T,
},
// Some are references
C(&'a str),
}
// What is expected to be generated
enum ButcheredFoo<'cow, 'a: 'cow, T: Clone> {
// Note that we are not creating Cow<'cow, String> here, perhaps thanks to
// an attribute macro
A(Cow<'cow, str>),
B {
// What is copy should be copied (defined with an attribute macro)
a: usize,
// What is uncertain should stay in a cow, but note the trait bound for
// T
b: Cow<'cow, T>,
},
// References are copy, so they should be copied, but note the trait bound
// for 'a
C(&'a str)
}
impl<'a, T: Clone> Foo<'a, T> {
fn butcher<'cow>(this: Cow<'cow, Foo<'a, T>>) -> ButcheredFoo<'cow, 'a, T> {
use Cow::*;
use Foo::*;
match this {
Borrowed(this) => match this {
A(a) => ButcheredFoo::A(Borrowed(a)),
B { a, b } => ButcheredFoo::B {
a: *a,
b: Borrowed(b),
},
C(a) => ButcheredFoo::C(a),
},
Owned(this) => match this {
A(a) => ButcheredFoo::A(Owned(a)),
B { a, b } => ButcheredFoo::B {
a,
b: Owned(b),
},
C(a) => ButcheredFoo::C(a),
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment