I'm reading the book Programming Rust, and learned about Rust's traits and generic types. And I find that type bounds can be placed on the methods of a trait. Then I constructed the following trait and implemented it for a struct.
use std::fmt::Display;
trait Test<T> {
fn show(&self)
where
T: Display;
fn test(&self);
}
struct S<T> {
field: T,
}
impl<T> Test<T> for S<T> {
fn show(&self)
where
T: Display,
{
println!("My field: {}", self.field);
}
fn test(&self) {
println!("Just for test");
}
}
The follwing code would not compile just as expected:
struct R;
fn main() {
let s = S { field: R {} };
s.show();
}
But the following code would compile and run.
struct R;
fn main() {
let s = S { field: R {} };
s.test();
}
Shouldn't Rust just reject the code when s
is defined as S { field: R{} }
? Does it mean that s
is an instance of S
that implements trait T
partially?
rustfmt
to format your code. You can find it under tools in the upper right corner on the playground. – hellow