gpt4 book ai didi

generics - 在 Rust 中接受 &Vec 和 &Vec<&T> 的函数

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

在我的结构中我有一个 from函数采用对 T 类型元素向量的共享引用并进行一些初始化。

fn from(t: &Vec<T>) -> () {
// ...
for a in t {
// ...
}
for a in t {
// ...
}
}

我还有另一个功能from_partial首先对 &Vec<T> 执行一些过滤并希望将这个简化的元素列表传递给 from .我不想克隆所以 from_partial将向量构造为 Vec<&T>而不是 Vec<T> .我也不想重复 from 中的逻辑因为所有需要做的就是遍历向量并获得 &T存储在某个地方。

在我的具体类型示例中,我可以同时分配 &Vec<&Bar>&Vec<Bar>from

let a: &Vec<&Bar> = &test.iter().collect();
let b: &Vec<Bar> = test;
Foo::from(a); // can assign &Vec<&Bar>
Foo::from(b); // can assign &Vec<Bar>

但是在使用泛型类型时,我无法这样做:

fn from_partial(t: &Vec<T>) -> () {
// Here a function is called that does some filtering on &Vec<T>
// and returns &Vec<&T>, but omitting for brevity.
let example: &Vec<&T> = &t.iter().collect();
Self::from(example); // cannot assign &Vec<&T> to &Vec<T>?
}

这是 MVCE(Playground):

struct Foo<T> {
t: T,
}
struct Bar {}

impl<T> Foo<T> {
fn from(t: &Vec<T>) -> () {
let mut v = Vec::new();
for a in t {
// ...
v.push(Foo { t: a })
}
for a in t {
// ...
v.get(0);
}
}

fn from_partial(t: &Vec<T>) -> () {
// Here a function is called that does some filtering on &Vec<T>
// and returns &Vec<&T>, but omitting for brevity.
let example: &Vec<&T> = &t.iter().collect();
Self::from(example); // cannot assign &Vec<&T> to &Vec<T>?
}
}

fn main() {}

fn test(test: &Vec<Bar>) {
let a: &Vec<&Bar> = &test.iter().collect();
let b: &Vec<Bar> = test;
Foo::from(a); // can assign &Vec<&Bar>
Foo::from(b); // can assign &Vec<Bar>
}

我可以在 T 上添加任何类型的约束吗?这将使这成为可能?从根本上防止我在 from 中复制完全相同的逻辑两次。

最佳答案

您需要替换 Self::from(example);Foo::from(example); .

考虑 TBar ,然后是你的 from_partial来电需要&Vec<Bar> .问题是 Self然后代表Foo::<Bar> ,但您正在尝试调用 from&Bar ,即你需要 Foo::<&Bar> .

fn from_partial(t: &Vec<T>) -> () {
let example: &Vec<&T> = &t.iter().collect();
Foo::from(example);
}

关于generics - 在 Rust 中接受 &Vec<T> 和 &Vec<&T> 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65498659/

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