rust - 如何实现一个特征
问题描述
我正在尝试实现一个名为AppendBar
. String
它的唯一功能是append_bar
。
据我了解,self
应该是一个String的实例。
trait AppendBar {
fn append_bar(self) -> Self;
}
impl AppendBar for String {
fn append_bar(self) -> Self{
self.clone().push_str("Bar")
}
}
fn main() {
let s = String::from("Foo");
let s = s.append_bar();
println!("s: {}", s); // "s: FooBar"
}
这显然不是这种情况,因为我收到以下错误:
error[E0308]: mismatched types
--> exercises/traits/traits1.rs:18:9
|
17 | fn append_bar(self) -> Self{
| ---- expected `std::string::String` because of return type
18 | self.clone().push_str("Bar")
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found `()`
谁能帮我理解我的误解?
解决方案
17 | fn append_bar(self) -> Self{
| ---- expected `std::string::String` because of return type
18 | self.clone().push_str("Bar")
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::string::String`, found `()`
是说它期望append_bar
返回 a String
,但self.clone().push_str("Bar")
计算结果为()
unit 类型。编译器错误是正确的,因为push_str
函数的类型是fn push_str(&mut self, string: &str)
,请注意它没有返回类型,而是改变了它的Self
参数。
相反,您需要推入字符串然后返回字符串,例如
impl AppendBar for String {
fn append_bar(mut self) -> Self{
self.push_str("Bar");
self
}
}
我也删除了,.clone()
因为它没有必要。append_bar
已经接受self
并因此获得了字符串值的所有权,因此您可以将其推入并返回,而无需克隆它。
推荐阅读
- python - print(sample_set.add('1232')) 输出为 None
- c# - 如何使用 ReactiveUI c# 异步验证 ViewModel 属性?
- javascript - 未捕获的类型错误:无法读取未定义的 highcharts-3d.src.js:306 的属性“animObject”
- google-apps-script - 整个项目中没有函数运行(Google App Script)
- python - 如何使用 gcloud storage.download 属性
- javascript - 有没有办法将 html 标签绑定到一些数组索引?
- flutter - 如何更新变量以显示一些文本,有延迟,然后更新另一个变量也显示文本?
- javascript - 如何在javascript中默认自动向现有对象添加新属性
- beautifulsoup - 如何在beautifulsoup中获取name的值
- linux - 无法在 Manjaro 中连接 MongoDB 服务器,退出代码为 100 时出错