在 `&str` 或 `String` 时将泛型限制为“类字符串”

问题描述 投票:0回答:1

我有一些代码,但问题归结为:

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

rust
1个回答
2
投票

在这种情况下,你根本不需要泛型。该函数不会产生通用的

Self
,它会产生一个特定的。

impl Default for Thing<&'static str> {
    fn default() -> Self {
        Self {
            this: "i am a `&'static str`"
        }
    }
}

此外,不要在结构定义上设置特征界限.

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.