string - 接受任何类型的字符串并将其视为不可变字符串并生成新的不可变字符串的 Rust 方法?

标签 string rust arguments traits

我是 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");

Playground

输出是一个拥有的字符串。这个值是否不可变(如 Rust 中的典型值)仅在调用站点起作用。

另见:

关于string - 接受任何类型的字符串并将其视为不可变字符串并生成新的不可变字符串的 Rust 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53517344/

相关文章:

c - 如何在 main 中返回指针到指针的指针?

java - 将输入文本值传递给 DecimalFormat 时出错

rust - 我正在安装 “parquet-schema: command not found”,尽管我已经完成了 cargo 安装拼花地板

python - Maturin 项目背后有 Python 绑定(bind)功能

postgresql - PostgreSQL 中函数参数的约束

JavaScript 可变数量的函数参数

c++ - double to std::cout 截断数据

c# - 检查字符串是否以给定字符串开头

MySQL 匹配查询不适用于 Urlencoded 字符串

rust - 如何修复 : value may contain references; add `' static` bound to `T`