gpt4 book ai didi

rust - 我如何实现一种方法来处理 &str、Box、Rc 等?

转载 作者:行者123 更新时间:2023-11-29 08:15:56 27 4
gpt4 key购买 nike

我有代码以某种方式转换字符串引用,例如取第一个字母

trait Tr {
fn trim_indent(self) -> Self;
}

impl<'a> Tr for &'a str {
fn trim_indent(self) -> Self {
&self[..1] // some transformation here
}
}

fn main() {
let s = "aaa".trim_indent();
println!("{}", s);
}

现在我正尝试将此代码概括为任何实现 AsRef<str> 的特定类型.我最后的尝试是

use std::ops::Deref;

trait Tr<'a> {
fn trim_indent(self) -> Deref<Target = str> + 'a + Sized;
}

impl<'a, T: AsRef<str>> Tr<'a> for T {
fn trim_indent(self) -> Deref<Target = str> + 'a + Sized {
self.as_ref()[..1] // some transformation here
}
}

fn main() {
let s = "aaa".trim_indent();
println!("{}", s);
}

我卡住了,因为没有 Sized我在编译时收到类型未知的错误,但带有 Size我收到一条错误消息,提示我无法显式使用标记特征。

最佳答案

无论您以什么类型开始,&str 的结束类型始终是 &str,因此您的返回类型需要是 &str.

然后是实现类型引用的特征,以便您可以将输入和输出生命周期联系在一起:

use std::rc::Rc;

trait Tr<'a> {
fn trim_indent(self) -> &'a str;
}

impl<'a, T> Tr<'a> for &'a T
where
T: AsRef<str> + 'a,
{
fn trim_indent(self) -> &'a str {
&self.as_ref()[..1] // Take the first **byte**
}
}

fn main() {
let s: &str = "aaa";
println!("{}", s.trim_indent());

let s: Box<str> = Box::from("bbb");
println!("{}", s.trim_indent());

let s: Rc<str> = Rc::from("ccc");
println!("{}", s.trim_indent());
}

在这种情况下,由于您列出的所有类型都实现了 Deref无论如何,您只需为 &str 实现特性,所有类型都可以使用它:

trait Tr {
fn trim_indent(&self) -> &str;
}

impl Tr for str {
fn trim_indent(&self) -> &str {
&self[..1]
}
}

另见:

关于rust - 我如何实现一种方法来处理 &str、Box<str>、Rc<str> 等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50464159/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com