Skip to content

Instantly share code, notes, and snippets.

@barosl
Created July 7, 2015 00:17
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 barosl/390952faeaf7f184aab0 to your computer and use it in GitHub Desktop.
Save barosl/390952faeaf7f184aab0 to your computer and use it in GitHub Desktop.
Implicit coercion rules in Rust
// A normal function that accepts a `&str`
fn a(_: &str) {}
// A normal function that accepts a *trait* that is implemented by `&str`
trait StringNeeded {}
impl<'a> StringNeeded for &'a str {}
fn b<X: StringNeeded>(_: X) {}
// A struct that stores a `&str`
#[allow(dead_code)]
struct C<'a> {
x: &'a str,
}
fn main() {
let x = "Hello".to_owned();
a(&x); // `&String` is auto-coerced to `&str`
//b(&x); // It errors; auto-coercion does not happen
b(&*x); // You should manually coerce `&String` to `&str`
C {
x: &x,
}; // Auto-coercion happens
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment