concept trait in category rust

appears as: traits, A trait, trait, traits, trait, The trait
Rust in Action

This is an excerpt from Manning's book Rust in Action.

Trait bounds refer to traits. A trait is a language feature that is analogous to an interface, protocol or contract. If you have a background in object-oriented programming, consider a trait to be an abstract base class. For now, it will suffice to say that traits enable types to advertise that they are using common behavior. All of Rust’s operations are defined with traits. For example, the addition operator (+) is defined as the std::ops::Add trait. Traits are properly introduced in chapter 3, and are progressively explained in depth during the course of the book.

A full example of defining a function with generic types, including a trait bound is provided at Listing 2. 18. The resulting executable prints out these three lines to the console:

We also discuss how to add methods to types with impl blocks. Lastly, we take a good look at traits, Rust’s system for defining interfaces.[1]

Listing 3. 17. Defining the bare bones of a Read trait for File. Shows the distinction between the trait keyword which is used for definitions and the impl keyword for attaching a trait to a specific type. (ch3/ch3-skeleton-read-trait.rs)
#![allow(unused_variables)] #1

#[derive(Debug)]
struct File;  #2

trait Read {  #3
    fn read(self: &Self, save_to: &mut Vec<u8>) -> Result<usize, String>;  #4
}

impl Read for File {
    fn read(self: &File, save_to: &mut Vec<u8>) -> Result<usize, String> {
        Ok(0)  #5
    }
}

fn main() {
    let f = File{};
    let mut buffer = vec!();
    let n_bytes = f.read(&mut buffer).unwrap();
    println!("{} byte(s) read from {:?}", n_bytes, f);
}

We’ll see many uses of traits throughout the course of the book. They underlie Rust’s generics system and the language’s robust type checking. With a little bit of abuse, they can also support a form of inheritance of the form that’s common in most object oriented languages. For now though, the thing to remember is that traits are common behavior that types opt into via the syntax: impl Trait for Type.