简体   繁体   English

如何在引用而不是引用值上调用特征方法?

[英]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.

相关问题 如何为结构体的引用实现 Add trait? - How do I implement the Add trait for a reference to a struct? Trait方法,可以实现返回引用或拥有值 - Trait method that can be implemented to either return a reference or an owned value 如何公开由类库引用的类库,该类库随后作为项目引用包含在Visual Studio中? - How do I expose class libraries referenced by a class library, which is then included as a project reference in Visual Studio? 如何在数组引用中使用索引作为Perl中的方法引用? - How do I use an index in an array reference as a method reference in Perl? 我如何获得原始值的参考? - how do i get a reference of primitive value? 如何在C#中将方法引用传递给其他方法 - How Do I Pass A Method Reference to A Different Method in C# 如何从if语句动态调用对象的引用名称? - How do I dynamically call a reference name of an object from an if statement? 使用ArrayList中的引用来调用方法,并更改引用对象的当前状态? - Use a reference inside an ArrayList to call a method, and change the current state of the referenced object? 如何将变量作为方法传递给Perl哈希引用? - How do I pass a variable as a method to a Perl hash reference? 如何确定DLL的引用位置? - How do I determine where DLL is referenced?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM