我是 Rust 新手。我想编写一个方法(特征实现?),它接受任何一个字符串或一个字符串切片,将其视为不可变的,并返回一个新的不可变字符串。假设 foo
是一种将您提供的任何输入加倍的方法:
let x = "abc".foo(); // => "abcabc"
let y = x.foo(); // => "abcabcabcabc"
let z = "def".to_string().foo(); // => "defdef"
在这种情况下,我不关心安全或性能,我只希望我的代码能够编译以进行一次性测试。如果堆无限增长,那就这样吧。如果这需要两个特征实现,那很好。
最佳答案
Let's say
foo
is a method that doubled whatever input you give it.
A trait是执行此操作的一种非常好的方法,因为它会产生一种常见的行为:
trait Foo {
fn foo(&self) -> String;
}
...应用于多种类型:
impl Foo for String {
fn foo(&self) -> String {
let mut out = self.clone();
out += self;
out
}
}
impl<'a> Foo for &'a str {
fn foo(&self) -> String {
let mut out = self.to_string();
out += self;
out
}
}
使用:
let x = "abc".foo();
assert_eq!(&x, "abcabc");
let z = "shep".to_string().foo();
assert_eq!(&z, "shepshep");
输出是一个拥有的字符串。这个值是否不可变(如 Rust 中的典型值)仅在调用站点起作用。
另见:
关于string - 接受任何类型的字符串并将其视为不可变字符串并生成新的不可变字符串的 Rust 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53517344/