Skip to content

Instantly share code, notes, and snippets.

@aturon
Last active August 29, 2015 14:10
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 aturon/fac0804d0560913111a8 to your computer and use it in GitHub Desktop.
Save aturon/fac0804d0560913111a8 to your computer and use it in GitHub Desktop.
trait CoerceFrom<T> {
fn coerce_from(T) -> Self;
}
trait Coerce {
fn coerce<T>(self) -> T where T: CoerceFrom<Self>;
}
impl<T> Coerce for T {
fn coerce<U: CoerceFrom<T>>(self) -> U {
CoerceFrom::coerce_from(self)
}
}
impl<'a> CoerceFrom<&'a String> for &'a str {
fn coerce_from(s: &'a String) -> &'a str {
s.as_slice()
}
}
impl<'a> CoerceFrom<&'a String> for &'a [u8] {
fn coerce_from(s: &'a String) -> &'a [u8] {
s.as_bytes()
}
}
fn main() {
let s = format!("hello");
// let b: &[u8] = s.coerce(); // fails
let b: &[u8] = (&s).coerce();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment