我有一些代码,但问题归结为:
pub struct Thing<S>
where S: AsRef<str> // im using AsRef here but the point is just that `S` is string-like
{
this: S
}
impl<S> Default for Thing<S>
where S: AsRef<str> {
fn default() -> Self {
Self {
this: "i am a `&'static str`"
}
}
}
货物说:
expected type parameter `S`
found reference `&'static str`
我知道这个问题与它是对
str
的引用有关,我只是真的不知道该怎么做。如何将泛型限制为“类似字符串”,同时确保所述泛型至少可以是 &str
或 String
?
在这种情况下,你根本不需要泛型。该函数不会产生通用的
Self
,它会产生一个特定的。
impl Default for Thing<&'static str> {
fn default() -> Self {
Self {
this: "i am a `&'static str`"
}
}
}
此外,不要在结构定义上设置特征界限.