Rust Traits
2024-11-12 22:07:03 +0000
A trait
is a collection of methods defined for an unknown type: Self
.
They can access other methods declared in the same trait
, and can be
implemented for any data type.
trait Foo<T> {
fn new() -> Self;
fn test(&self, s: &String);
}
struct Bar<T> {
value: T
}
impl<T> Foo<T> for Bar<T>
where
T: Sized
{
fn new() -> Self {
Bar {
value: 1
}
}
fn test(&self, s: &String) {
println!(s);
}
}
let bar: Bar = Bar::<i32>::new();
bar.test(format!("hello"));