我定义了一个特征:
pub trait SaySomething {
fn say(&self) {
println!("{:?} can't speak", self);
}
}
我得到了错误:
error[E0277]: `Self` doesn't implement `std::fmt::Debug`
--> src/lib.rs:3:38
|
3 | println!("{:?} can't speak", self);
| ^^^^ `Self` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
|
= help: the trait `std::fmt::Debug` is not implemented for `Self`
= help: consider adding a `where Self: std::fmt::Debug` bound
= note: required because of the requirements on the impl of `std::fmt::Debug` for `&Self`
= note: required by `std::fmt::Debug::fmt`
所以我尝试了:
use std::fmt::Debug;
pub trait SaySomething {
fn say<Self: Debug>(self: &Self) {
println!("{:?} can't speak", self);
}
}
我得到了错误:
error: expected identifier, found keyword `Self`
--> src/lib.rs:4:12
|
4 | fn say<Self: Debug>(self: &Self) {
| ^^^^ expected identifier, found keyword
error[E0194]: type parameter `Self` shadows another type parameter of the same name
--> src/lib.rs:4:12
|
3 | / pub trait SaySomething {
4 | | fn say<Self: Debug>(self: &Self) {
| | ^^^^ shadows another type parameter
5 | | println!("{:?} can't speak", self);
6 | | }
7 | | }
| |_- first `Self` declared here
error[E0307]: invalid method receiver type: &Self
--> src/lib.rs:4:31
|
4 | fn say<Self: Debug>(self: &Self) {
| ^^^^^
|
= note: type must be `Self` or a type that dereferences to it
= help: consider changing to `self`, `&self`, `&mut self`, or `self: Box<Self>`
答案 0 :(得分:0)
您需要将特征限制为实现Debug
的类型。
pub trait SaySomething: std::fmt::Debug {
fn say(&self) {
println!("{:?} can't speak", self);
}
}