rust:泛型函数参数类型演绎

1l5u6lss  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(77)

我正在阅读一本关于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

7xzttuei

7xzttuei1#

Display有一个用于参考的全面实现:

impl<T> Display for &T where
    T: Display + ?Sized

字符串
在对show_it_generic(&s)的调用中,Rust首先匹配这个blanket实现,然后检查引用的类型T是否实现了Display-在您的情况下,它没有实现。

相关问题