[英]How do I call a trait method on a reference and not the referenced value?
I have a reference ( foo
) that implements the trait IntoIterator<Item = &T>
. 我有一个实现特征
IntoIterator<Item = &T>
的引用( foo
)。 I want to call the trait method into_iter
directly on foo
(ie the reference itself) and not *foo
(the referenced value), as seems to be happening, since the type of *foo
also implements IntoIterator
(albeit with Item = T
). 我想直接在
foo
(即引用本身)而不是*foo
(引用的值)上调用trait方法into_iter
,这似乎正在发生,因为*foo
的类型还实现了IntoIterator
(尽管Item = T
)。 I've tried UFCS, but even that doesn't seem to do the trick. 我已经尝试过UFCS,但即使这样似乎也不能解决问题。
Here's my actual code: 这是我的实际代码:
fn csl_join<'a, V, T>(value: &V) -> String
where V: IntoIterator<Item = &'a T>,
T: 'a + ToString
{
itertools::join(value.into_iter().map(|v: &T| v.to_string()), ",")
}
I ended up solving this issue just after posting it, thanks to @LukasKalbertodt's helpful comments. 由于@LukasKalbertodt的有用评论,我在发布此问题后最终解决了该问题。 It turns out I simply wanted the type bound to be
&V: IntoIterator<Item = &T>
, to match the intended usage in the function body (duh!). 事实证明,我只是希望类型绑定为
&V: IntoIterator<Item = &T>
,以匹配函数体中的预期用法(duh!)。
So the code becomes: 因此,代码变为:
fn csl_join<'a, 'b, V, T>(value: &'a V) -> String
where V: 'a,
&'a V: IntoIterator<Item = &'b T>,
T: ToString + 'b
{
itertools::join(value.into_iter().map(|v: &T| v.to_string()), ",")
}
I'll leave this here in case it assists someone else, by chance. 我会把它留在这里,以防它偶然帮助别人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.