Skip to content

Instantly share code, notes, and snippets.

@barosl barosl/
Created Jul 7, 2015

What would you like to do?
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`
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
You can’t perform that action at this time.