[英]Rust method that accepts and treats any kind of string as immutable and produces a new immutable string?
我是Rust的新手。 我想编写一个方法(特征实现?),该方法接受String或字符串切片中的任何一个,将其视为不可变的,并返回一个新的不可变的字符串。 假设foo
是一种将输入的内容加倍的方法:
let x = "abc".foo(); // => "abcabc"
let y = x.foo(); // => "abcabcabcabc"
let z = "def".to_string().foo(); // => "defdef"
在这种情况下,我不在乎安全性或性能,我只想编译我的代码以进行一次性测试。 如果堆无限增长,那就这样吧。 如果这需要两个特质实现,那就很好。
假设
foo
是一种将输入的内容加倍的方法。
特质是实现此目的的一种非常好的方法,因为它具有一种常见的行为:
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中的典型值)仅在调用站点起作用。
也可以看看:
如果您想在末尾借用字符串&str
:
trait Foo {
fn display(&self);
}
impl<T> Foo for T where T: AsRef<str> {
fn display(&self) {
println!("{}", self.as_ref());
}
}
fn main() {
"hello".display();
String::from("world").display();
}
如果您想要拥有的String
:
trait Foo {
fn display(self);
}
impl<T> Foo for T where T: Into<String> {
fn display(self) {
let s: String = self.into();
println!("{}", s);
}
}
fn main() {
"hello".display();
String::from("world").display();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.