接受任何类型的字符串并将其视为不可变字符串并生成新的不可变字符串的 Rust 方法?
Rust method that accepts and treats any kind of string as immutable and produces a new immutable string?
我是 Rust 新手。我想编写一个方法(特征实现?),它接受任何一个字符串或一个字符串切片,将其视为不可变的,并且 returns 一个新的不可变字符串。假设 foo
是一种将您提供的任何输入加倍的方法:
let x = "abc".foo(); // => "abcabc"
let y = x.foo(); // => "abcabcabcabc"
let z = "def".to_string().foo(); // => "defdef"
在这种情况下,我不关心安全性或性能,我只希望我的代码编译为一次性测试。如果堆无限增长,那就这样吧。如果这需要两个特征实现,那很好。
如果你想在末尾借用字符串&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();
}
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 中的典型值)仅在调用站点起作用。
另请参阅:
我是 Rust 新手。我想编写一个方法(特征实现?),它接受任何一个字符串或一个字符串切片,将其视为不可变的,并且 returns 一个新的不可变字符串。假设 foo
是一种将您提供的任何输入加倍的方法:
let x = "abc".foo(); // => "abcabc"
let y = x.foo(); // => "abcabcabcabc"
let z = "def".to_string().foo(); // => "defdef"
在这种情况下,我不关心安全性或性能,我只希望我的代码编译为一次性测试。如果堆无限增长,那就这样吧。如果这需要两个特征实现,那很好。
如果你想在末尾借用字符串&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();
}
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 中的典型值)仅在调用站点起作用。
另请参阅: