rust - 在特质 impl 中理解自我
问题描述
我对自己有点困惑。你能帮我吗?我试图将新值追加或推送到vec
. 这仅表明我不知道自我实际上是什么。我得到的错误是:
---- ^^^^ this call modifies `self` in-place
| |
| you probably want to use this value after calling the method...
= note: ...instead of the `()` output of method `push`
为什么以下工作但......
trait AppendBar {
fn append_bar(self) -> Self;
}
impl AppendBar for String {
fn append_bar(self) -> Self{
self.to_string() + "Bar"
}
}
这和...
impl AppendBar for Vec<String> {
fn append_bar(self) -> Self{
let mut bar = vec![String::from("Bar")];
bar.push(self);
bar
}
}
这和...
impl AppendBar for Vec<String> {
fn append_bar(self) -> Self{
let bar_vec = vec!["Bar".to_string()];
self.append(bar_vec)
}
}
这不?
trait AppendBar<T> {
fn append_bar(self) -> Self;
}
impl<T> AppendBar<T> for Vec<T> {
fn append_bar(self) -> Self{
self.push("Bar".to_string())
}
}
解决方案
impl AppendBar for Vec<String> {
fn append_bar(self) -> Self{
let mut bar = vec![String::from("Bar")];
bar.push(self);
bar
}
}
因为self
是 aVec<String>
并且您不能将 a 推Vec<String>
入 a Vec<String>
(错误消息告诉您:“预期String
得到Vec<String>
”)。
impl AppendBar for Vec<String> {
fn append_bar(self) -> Self{
let bar_vec = vec!["Bar".to_string()];
self.append(bar_vec)
}
}
因为Vec::append
什么都不返回,所以你需要self
自己返回(或者&mut self
作为参数什么都不返回)。
impl<T> AppendBar<T> for Vec<T> {
fn append_bar(self) -> Self{
self.push("Bar".to_string())
}
}
因为"Bar".to_string()
不保证T
对所有类型都是 a T
。
推荐阅读
- java - 在 Eclipse WindowBuilder 编辑器中,“设计”选项卡没有显示任何内容
- node.js - TypeError: mongoose.schema 不是构造函数
- javascript - 如何在另一个函数中调用 Classes 函数
- azure - Azure DevOps – 到 Intranet TFS 2018 的管道:SSL_ERROR_SYSCALL
- mysql - SQL SELECT 多个表中的多个数据
- python - Python 并发期货 ProcessPoolExecutor 和全局变量:在 Linux 上工作,在 MacOS 上出错
- c# - 如何在 UWP 中使 CommandBar 指向下方
- winforms - 为什么组合框显示对象?
- python - 为什么我从这个 python 代码中得到一个错误?
- postgresql - 无法使用 aws_s3.query_export_to_s3 函数在 S3 中将 AWS RDS Postgres 表导出为 CSV