Wednesday, May 19, 2021

Implementing Traits in Rust


What are traits in Rust 

A trait is a collection or group of methods defined for an unknown type: Self. They can access other methods declared in the same trait. Trait similar to abstract classes in C++. 


 Implementing a trait

A trait is implemented similarly to an inherent implementation except that a trait name and the for keyword follow the impl keyword before the type name. Let’s implement an built-in trait called ToString on a Person struct:



struct Person {
    name: String,
    age: u32,
    address: String,
}

// Implementing an in-built trait ToString on the Person struct
impl ToString for Person {
    fn to_string(&self) -> String {
        return format!(
            "{} is  {} years old and live in {}.",
            self.name, self.age, self.address
        );
    }
}

fn main() {
    let person = Person {
        name: "Addies".to_string(),
        age: 17,
        address: "Jakarta".to_string(),
    };
    println!("{}", person.to_string());
}


you may run by compiling with cargo build and cargo run. Result shown as below      






No comments:

Post a Comment