我正在阅读一本关于Rust的书,偶然发现了一个看起来像这样的例子。
use std::ops::{Deref, DerefMut};
use std::fmt::Display;
struct Selector<T> {
elements: Vec<T>,
current: usize
}
impl<T> Deref for Selector<T> {
type Target = T;
fn deref(&self) -> &T {
&self.elements[self.current]
}
}
impl<T> DerefMut for Selector<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.elements[self.current]
}
}
fn show_it_generic<T: Display> (thing: T) {
println!("{}", thing);
}
fn main() {
let s = Selector {elements: vec!["good", "bad", "ugly"], current: 2};
show_it_generic(&s);
}
字符串
编译器告诉我类型T
被推断为Selector<&str>
,但我对此有点困惑。我相信它应该是&Selector<&str>
。为什么会出现下面的错误?
error[E0277]: `Selector<&str>` doesn't implement `std::fmt::Display`
--> src/main.rs:28:22
|
28 | show_it_generic(&s);
| --------------- ^ `Selector<&str>` cannot be formatted with the default formatter
| |
| required by a bound introduced by this call
|
= help: the trait `std::fmt::Display` is not implemented for `Selector<&str>`
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
= note: required for `&Selector<&str>` to implement `std::fmt::Display`
note: required by a bound in `show_it_generic`
--> src/main.rs:22:23
|
22 | fn show_it_generic<T: Display> (thing: T) {
| ^^^^^^^ required by this bound in `show_it_generic`
help: consider dereferencing here
|
28 | show_it_generic(&*s);
| +
For more information about this error, try `rustc --explain E0277`.
error: could not compile `code1` (bin "code1") due to previous error
型
1条答案
按热度按时间7xzttuei1#
Display
有一个用于参考的全面实现:字符串
在对
show_it_generic(&s)
的调用中,Rust首先匹配这个blanket实现,然后检查引用的类型T
是否实现了Display
-在您的情况下,它没有实现。