Generics 在另一个泛型结构上创建泛型结构

Generics 在另一个泛型结构上创建泛型结构,generics,struct,rust,dereference,Generics,Struct,Rust,Dereference,我试图在Rust中创建一个结构,它本身相对于其他通用结构是通用的。这很令人困惑,希望这个例子能让事情变得更清楚: use std::ops::Deref; use std::rc::Rc; struct Foo<T: Deref> { val: T<i32>, other: i32, } impl<T> Foo<T> { pub fn new(&self, val: T<i32>, other: i3

我试图在Rust中创建一个结构,它本身相对于其他通用结构是通用的。这很令人困惑,希望这个例子能让事情变得更清楚:

use std::ops::Deref;
use std::rc::Rc;

struct Foo<T: Deref> {
    val: T<i32>,
    other: i32,
}

impl<T> Foo<T> {
    pub fn new(&self, val: T<i32>, other: i32) -> Self {
        Foo {val: val, other: other}
    }
}

fn main() {
    let foo = Foo::new(Rc::new(0), 0);
}
使用std::ops::Deref;
使用std::rc::rc;
结构Foo{
瓦尔:T,
其他:i32,
}
impl-Foo{
发布fn新建(&self,val:T,other:i32)->self{
Foo{val:val,other:other}
}
}
fn main(){
设foo=foo::new(Rc::new(0),0);
}


我希望能够使用
Rc
对象或
Arc
对象调用
new
来创建
Foo
对象,具体取决于我是否需要线程安全。但是,当我尝试此操作时,会出现以下错误:
error[E0109]:此类型上不允许使用类型参数
,因为编译器抱怨
val:T,
中的
i32
。这在铁锈中可能吗?如果是这样,我是否可以安全地调用
i32
上的方法,假设它将自动取消引用它?

该语法没有意义,但此版本编译:

use std::ops::Deref;
use std::rc::Rc;
use std::sync::Arc;

struct Foo<T> {
    val: T,
    other: i32,
}

impl<T> Foo<T>
    where T: Deref<Target = i32>
{
    pub fn new(val: T, other: i32) -> Self {
        Foo {
            val: val,
            other: other,
        }
    }
}

fn main() {
    let foo = Foo::new(Rc::new(0), 0);
    let foo = Foo::new(Arc::new(0), 0);
}

一般来说,类似的概念

struct Foo<T> {
    val: T<i32>,
}
structfoo{
瓦尔:T,
}

那就没用了。仅仅因为某些东西是通过
i32
参数化的,并不意味着你可以用
i32
做任何事情。同样,类型可以用
i32
(或者根本不用)以外的参数化,并且仍然可以让您访问
i32

真棒,谢谢您的帮助!我现在要试试这个。我认为这将是一种更常见的技术,可以快速获得线程安全的或不依赖于您的需要的通用结构,您经常看到这一点吗?与其他一些语言不同,遗憾的是Rust(尚未)没有更高级的类型,因此类型参数必须是具体的类型。但是在这种情况下,我同意@Shepmaster的说法,即您不需要它。
struct Foo<T> {
    val: T<i32>,
}