Skip to content

Instantly share code, notes, and snippets.

@igor04
Last active August 29, 2015 14:06
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 igor04/9cc607e60021031da553 to your computer and use it in GitHub Desktop.
Save igor04/9cc607e60021031da553 to your computer and use it in GitHub Desktop.
rust
// 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