Created
July 7, 2015 00:17
-
-
Save barosl/390952faeaf7f184aab0 to your computer and use it in GitHub Desktop.
Implicit coercion rules in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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