Generics 同时接受&;Vec<;T>;及;Vec<&;T>;锈迹斑斑
在我的结构中,我有一个Generics 同时接受&;Vec<;T>;及;Vec<&;T>;锈迹斑斑,generics,rust,Generics,Rust,在我的结构中,我有一个from函数,它对T类型的元素向量进行共享引用,并进行一些初始化 fn from(t: &Vec<T>) -> () { // ... for a in t { // ... } for a in t { // ... } } 但是,在使用泛型类型时,我无法这样做: fn from_partial(t: &Vec<T>) -> () { //
from
函数,它对T
类型的元素向量进行共享引用,并进行一些初始化
fn from(t: &Vec<T>) -> () {
// ...
for a in t {
// ...
}
for a in t {
// ...
}
}
但是,在使用泛型类型时,我无法这样做:
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 from_partial(t:&Vec)->(){
//这里调用了一个函数,它对&Vec执行一些过滤
//并返回&Vec,但为简洁起见省略。
例如:&Vec=&t.iter().collect();
Self::from(示例);//无法将&Vec分配给&Vec?
}
这里是MVCE():
structfoo{
t:t,
}
结构条{}
impl-Foo{
fn从(t:&Vec)->(){
让mut v=Vec::new();
一个小时{
// ...
v、 推送(Foo{t:a})
}
一个小时{
// ...
v、 get(0);
}
}
fn来自_partial(t:&Vec)->(){
//这里调用了一个函数,它对&Vec执行一些过滤
//并返回&Vec,但为简洁起见省略。
例如:&Vec=&t.iter().collect();
Self::from(示例);//无法将&Vec分配给&Vec?
}
}
fn main(){}
fn测试(测试:&Vec){
设a:&Vec=&test.iter().collect();
设b:&Vec=test;
Foo::from(a);//可以分配&Vec
Foo::from(b);//可以分配&Vec
}
我是否可以在
T
上添加任何类型的约束来实现这一点?为了从根本上防止我在from
中重复两次完全相同的逻辑。您需要替换Self::from(示例)代码>带有Foo::from(示例)代码>
假设T
是Bar
,那么您的from_partial
调用将使用&Vec
。问题是,Self
然后表示Foo:
,但您正试图使用和
从调用,即您需要Foo:
fn from_partial(t:&Vec)->(){
例如:&Vec=&t.iter().collect();
Foo::from(示例);
}
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>?
}
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>
}