Back to Comprehensive Rust

Traits

src/methods-and-traits/traits.md

latest667 B
Original Source
<!-- Copyright 2023 Google LLC SPDX-License-Identifier: CC-BY-4.0 -->

Traits

Rust lets you abstract over types with traits. They're similar to interfaces:

rust,editable
# // Copyright 2023 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
trait Pet {
    /// Return a sentence from this pet.
    fn talk(&self) -> String;

    /// Print a string to the terminal greeting this pet.
    fn greet(&self);
}
<details>
  • A trait defines a number of methods that types must have in order to implement the trait.

  • In the "Generics" segment, next, we will see how to build functionality that is generic over all types implementing a trait.

</details>