mirror of
https://github.com/rust-lang/rustlings
synced 2024-11-01 09:20:11 +00:00
1663a16ead
Co-authored-by: zhangshaozhi <zhangshaozhi@ZhangshaozhideMacBook-Pro.local> |
||
---|---|---|
.. | ||
README.md | ||
traits1.rs | ||
traits2.rs |
Traits
A trait is a collection of methods.
Data types can implement traits. To do so, the methods making up the trait are defined for the data type. For example, the String
data type implements the From<&str>
trait. This allows a user to write String::from("hello")
.
In this way, traits are somewhat similar to Java interfaces and C++ abstract classes.
Some additional common Rust traits include:
Clone
(theclone
method)Display
(which allows formatted display via{}
)Debug
(which allows formatted display via{:?}
)
Because traits indicate shared behavior between data types, they are useful when writing generics.