代码之家  ›  专栏  ›  技术社区  ›  mikemaccana

我用trait扩展了一个类型,为什么我的Vec<impl ThatTrait>不接受实现该trait的类型?

  •  1
  • mikemaccana  · 技术社区  · 11 月前

    我有个特点 Input 这增加了一个 to_custom_bytes() 方法to String s和 u64 s

    trait Input {
        fn to_custom_bytes(&self) -> Vec<u8>;
    }
    
    impl Input for u64 {
        fn to_custom_bytes(&self) -> Vec<u8> {
            self.to_le_bytes().to_vec()
        }
    }
    
    impl Input for String {
        fn to_custom_bytes(&self) -> Vec<u8> {
            self.as_bytes().to_vec()
        }
    }
    

    我有一个函数,它接受实现该特征的项目向量:

    fn inputs_to_custom_bytes(inputs: Vec<impl Input>) -> Vec<u8> {
        let mut bytes: Vec<u8> = Vec::new();
        for input in inputs {
            bytes.extend(input.to_custom_bytes());
        }
        bytes
    }
    

    Rust编译器为什么抱怨 expected 'String', found 'u64' 对于age,当age实现这个Trait并且参数为 Vec<impl Input> Vec<String> ?

    pub fn main() {
        let name = String::from("steve");
        let age: u64 = 20;
        let custom_bytes: Vec<u8> = inputs_to_custom_bytes(vec![name, age]);
    }
    
    
    1 回复  |  直到 11 月前
        1
  •  2
  •   mikemaccana    11 月前

    impl 在通用参数中意味着 这种类型,因此不能同时用于多种类型。因此,函数接受 Vec<impl Input> 可以用a来调用 Vec<u64> 或a Vec<String> ,但没有指定具体类型 Vec<impl输入> ;这是一个泛型类型参数。

    dyn 可以代替 impl ,对于允许混合多种类型值的trait对象,使用运行时查找在运行时调用正确的函数。所以你应该能够用一个 Vec<&dyn Input> .

    pub fn inputs_to_custom_bytes(inputs: Vec<&dyn Input>) -> Vec<u8> {
        let mut bytes: Vec<u8> = Vec::new();
        for input in inputs {
            bytes.extend(input.to_seeds());
        }
        bytes
    }