gpt4 book ai didi

rust - 为什么即使我已经实现了 Trait<&str>,特征绑定(bind) Trait<&String> 仍然不满足?

转载 作者:行者123 更新时间:2023-11-29 08:16:33 26 4
gpt4 key购买 nike

我写了下面的代码:

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指定了生命周期,编译器还是找不到正确的实现?我该如何解决这个问题?

最佳答案

How can I fix this?

通过获取 &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 的实现并使用 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);
}

关于rust - 为什么即使我已经实现了 Trait<&str>,特征绑定(bind) Trait<&String> 仍然不满足?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38903378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com