Last active
August 29, 2015 14:06
-
-
Save igor04/9cc607e60021031da553 to your computer and use it in GitHub Desktop.
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
// file_1.rs | |
// | |
// implement class method and instance method with the same name | |
// | |
struct Car { | |
stamp: &'static str | |
} | |
impl Car { | |
fn print() { | |
println!("It is Car class method!") | |
} | |
} | |
trait Print { | |
fn print(&self) -> (); | |
} | |
impl Print for Car { | |
fn print(&self) { | |
println!("It is Car instance method") | |
} | |
} | |
fn main() { | |
let car = Car { stamp: "BMW" }; | |
Car::print(); | |
car.print(); | |
} | |
// file_2.rs | |
// | |
// traits couldn't implement class methods | |
// but could implement class methods which return Self (because with | |
// type it knows what implementation should use) | |
// | |
struct Car { | |
stamp: &'static str | |
} | |
impl Car { | |
fn print(&self) { | |
println!("It is Car instance with stamp: {}", self.stamp) | |
} | |
} | |
trait Face { | |
fn print() -> (); | |
fn new(var: &'static str) -> Self; | |
} | |
impl Face for Car { | |
fn print() { | |
println!("It is Car class method!") | |
} | |
fn new(var: &'static str) -> Car { | |
Car { stamp: var } | |
} | |
} | |
fn main() { | |
// Car::print(); // first-class methods are not supported | |
// Face::print(); // cannot determine a type for this bounded type parameter: unconstrained type | |
// let car = Face::new("BMV"); // cannot determine a type for this bounded type parameter: unconstrained type | |
let car: Car = Face::new("BMV"); | |
car.print(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment