Rust study notes 6.1 traits and generics (Trait && generics)

6.1 Trait && generics

Traits

  • Similar to interfaces and abstract classes
  • Add defined behavior to the structure
impl trait_demo for struct_demo
struct Steve {
    
    
    name: String,
}

impl Person for Steve {
    
    
    fn new(name_str: String) -> Self {
    
    
        Steve {
    
     name: name_str }
    }

    fn language(&self) -> &str {
    
    
        "Steve"
    }
}

struct Alex {
    
    
    name: String,
}

impl Person for Alex {
    
    
    fn new(name_str: String) -> Self {
    
    
        Alex {
    
     name: name_str }
    }

    fn language(&self) -> &str {
    
    
        "Alex"
    }
    fn eat_food(&self) {
    
    
        println!("Eat fish!");
    }
}

trait Person {
    
    
    fn new(name_str: String) -> Self;
    fn language(&self) -> &str;
    fn eat_food(&self) {
    
    
        println!("Eat food");
    }
}

fn main() {
    
    
    let a = Steve::new("Star_tears".to_string());
    let b = Alex::new("T_dream".to_string());
    a.eat_food();
    b.eat_food();
}

  • return enumeration

    • fn get_trait -> Box<dyn trait_name>
      

generic

  • Generic programming ( generic programming) is a style or paradigm of a programming language
  • Generics allow programmers to use some later-specified types when writing code in a strongly typed programming language, and specify these types as parameters when instantiating
trait Bark {
    
    
    fn bark(&self) -> String;
}

struct Dog {
    
    
    species: String,
}

struct Cat {
    
    
    color: String,
}

impl Bark for Dog {
    
    
    fn bark(&self) -> String {
    
    
        format!("{} barking", self.species)
    }
}

fn bark<T: Bark>(b: T) {
    
    
    println!("{}", b.bark());
}

fn main() {
    
    
    let dog = Dog {
    
    
        species: "white dog".to_string(),
    };
    bark(dog);
}

Guess you like

Origin blog.csdn.net/qq_51173321/article/details/126071093