gpt4 book ai didi

rust - 在循环中/分配: expected type parameter `T` ,找到了 `&T`

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

error on playground

enum Error {}

fn foo<T>(bars: Vec<T>) -> Result<Vec<T>, Error>
{
let mut baz = vec![];
for bar in bars.iter(){
baz.push(bar);
}
Ok(baz)
}
像&或*这样的东西似乎无法解决,也因为 bar是外部包装箱
enum Error {}

fn foo<T>(bars: Vec<T>) -> Result<Vec<T>, Error>
{
let mut baz = vec![];
for &bar in bars.iter(){
baz.push(bar);
}
Ok(*baz)
}
是什么原因引起的?它将如何运作?

最佳答案

solution in playground
问题是,.iter()总是返回引用值。
the reference显示以下内容:

There are three common methods which can create iterators from a collection:

iter(), which iterates over &T.
iter_mut(), which iterates over &mut T.
into_iter(), which iterates over T.
enum Error {}

fn foo<T>(bars: Vec<T>) -> Result<Vec<T>, Error>
{
let mut baz = vec![];
for bar in bars.into_iter(){
baz.push(bar);
}
Ok(baz)
}

关于rust - 在循环中/分配: expected type parameter `T` ,找到了 `&T`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64484844/

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