Monday, September 15, 2014

Rust: some notation about Trait methods

// 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();
}

 
 
Blogger Templates