gpt4 book ai didi

rust - 将特征实现从&T推广到AsRef 的生命周期

转载 作者:行者123 更新时间:2023-12-03 11:36:29 25 4
gpt4 key购买 nike

我在将适用于&str的特征推广到其他字符串类型(例如Rc<str>Box<str>String)时遇到一些问题。
首先,我的示例函数应适用于:

assert_eq!(count("ababbc", 'a'), 2);                // already working
assert_eq!(count(Rc::from("ababbc"), 'a'), 2); // todo
assert_eq!(count("ababbc".to_string(), 'a'), 2); // todo
这是工作代码,它使第一次测试运行:
pub trait Atom: Copy + Eq + Ord + Display + Debug {}
impl Atom for char {}

pub trait Atoms<A, I>
where
I: Iterator<Item = A>,
A: Atom,
{
fn atoms(&self) -> I;
}

impl<'a> Atoms<char, std::str::Chars<'a>> for &'a str {
fn atoms(&self) -> std::str::Chars<'a> {
self.chars()
}
}

pub fn count<I, A, T>(pattern: T, item: A) -> usize
where
A: Atom,
I: Iterator<Item = A>,
T: Atoms<A, I>,
{
pattern.atoms().filter(|i| *i == item).count()
}
为了使下一个测试运行,我通过以下方式更改了 countAtoms的签名:
pub trait Atoms<'a, A, I>
where
I: Iterator<Item = A> + 'a,
A: Atom,
{
fn atoms<'b>(&'b self) -> I
where
'b: 'a;
}

impl<'a, S> Atoms<'a, char, std::str::Chars<'a>> for S
where
S: AsRef<str> + 'a,
{
fn atoms<'b>(&'b self) -> std::str::Chars<'b>
where
'b: 'a,
{
self.as_ref().chars()
}
}
但是现在函数计数不再编译了:
pub fn count<'a, I, A, T>(pattern: T, item: A) -> usize
where
A: Atom,
I: Iterator<Item = A> + 'a,
T: Atoms<'a, A, I>,
{
pattern.atoms().filter(|i| *i == item).count()
}
Playground-Link
编译器错误是: the parameter type 'T' may not live long enough ... consider adding an explicit lifetime bound...: 'T: 'a'。这对我来说不是完全可以理解的,因此我尝试应用了 T: Atoms<'a, A, I> + 'a帮助。现在错误是: 'pattern' does not live long enough ... 'pattern' dropped here while still borrowed
由于后一种错误也发生在没有实现 Atoms的情况下,而只是用 pattern.atoms();return 1;替换了函数主体,因此我怀疑 Atoms的类型签名不适合我的目的。
有没有人暗示 Atomscount的类型签名有什么问题?

最佳答案

trait Atoms<'a, A, I> where I: Iterator<Item = A> + 'a ...
通过编写此代码,您需要迭代器在生存期 'a内使 超过。由于 'a是特征的通用参数的一部分,因此它必须是可以延长使用期限的,然后才能开始(隐式)使用 <String as Atoms<'a, char, std::str::Chars>>::atoms。这与返回新的迭代器对象的想法直接矛盾,因为该对象在调用 atoms()之前不存在。
不幸的是,我不确定如何重写它,使其在没有通用关联类型(尚未稳定的功能)的情况下也能正常工作,但我希望至少对此问题的解释有所帮助。

关于rust - 将特征实现从&T推广到AsRef <T>的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65625748/

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