为什么特质绑定Trait<& String>即使我已经实施了Trait<& str>?

时间:2016-08-11 18:10:39

标签: rust lifetime

我写了以下代码:

pub struct Serializer;

pub trait Serialize<T> {
    fn to_bert(&self, data: T) -> Vec<u8>;
}

pub trait Convert<T> {
    fn to_binary(&self, data: T) -> Vec<u8>;
}

impl<'a> Convert<&'a str> for Serializer {
    fn to_binary(&self, data: &'a str) -> Vec<u8> {
        let binary_string = data.as_bytes();
        let binary_length = binary_string.len() as i16;
        let mut binary = vec![];
        binary.write_i16::<BigEndian>(binary_length).unwrap();
        binary.extend(binary_string.iter().clone());
        binary
    }
}

impl Serialize<String> for Serializer {
    fn to_bert(&self, data: String) -> Vec<u8> {
        let binary_string = self.to_binary(&data);
        self.generate_term(BertTag::String, binary_string)
    }
}

impl<'a> Serialize<&'a str> for Serializer {
    fn to_bert(&self, data: &'a str) -> Vec<u8> {
        let binary_string = self.to_binary(data);
        self.generate_term(BertTag::String, binary_string)
    }
}

编译时,我收到一条错误,指出编译器找不到正确的调用函数:

error: the trait bound `serializers::Serializer: serializers::Convert<&std::string::String>` is not satisfied [E0277]
let binary_string = self.to_binary(&data);
                         ^~~~~~~~~
help: run `rustc --explain E0277` to see a detailed explanation
help: the following implementations were found:
help:   <serializers::Serializer as serializers::Convert<&'a str>>
help:   <serializers::Serializer as serializers::Convert<types::BertType>>

为什么在我指定生命周期&str时编译器找不到正确的实现?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

  

我该如何解决这个问题?

&str获取data

let binary_string = self.to_binary(&*data);

如错误所述,Convert<&String>未实现Serializer,但Convert<&str>&data&String&str,但您需要&*data,撰写&str会产生String

请注意,一般情况下(当字符串未更改时),不必为&str&str实现相同的功能,只有Serialize<String>版本应该足够。在您的示例中,您可以删除Serializer的{​​{1}}实施,并改为使用Serialize<&str>

fn main() {
    let mut s = Serializer;
    let a: String = "a".to_string();
    // autoderef &String to &str and call Serialize<&str>::to_bert()
    // I don't know why the autoderef does not work in your original example
    s.to_bert(&a);
}