简体   繁体   English

创建一个在另一个通用结构上通用的结构

[英]Create a struct that is generic over another generic struct

I am trying to create a struct in Rust that is itself generic with respect to other generic structs. 我正在尝试在Rust中创建一个结构,该结构本身相对于其他通用结构而言是通用的。 That's pretty confusing so hopefully this example will makes things clearer: 这非常令人困惑,因此希望此示例可以使事情变得更清楚:

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);
}

playground 操场

I would like to be able to create a Foo object by calling new with either Rc<i32> objects or Arc<i32> objects depending on whether I need thread safety or not. 我希望能够通过使用Rc<i32>对象或Arc<i32>对象调用new来创建Foo对象,具体取决于我是否需要线程安全。 I get the following error when I try this though: error[E0109]: type parameters are not allowed on this type , as the compiler complains about the i32 in val: T<i32>, . 我尝试这样做时会收到以下错误: error[E0109]: type parameters are not allowed on this type ,因为编译器抱怨val: T<i32>,i32 val: T<i32>, Is this possible in Rust? 在Rust中这可能吗? If so, can I safely call methods on i32 assuming it will auto dereference it? 如果是这样,我可以安全地在i32上调用方法(假设它会自动取消引用)吗?

That syntax doesn't make sense, but this version compiles: 该语法没有意义,但是此版本可以编译:

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);
}

Note how the trait bounds read: T: Deref<Target = i32> "Any T that implements Deref with a Target of an i32 ". 注意该性状边界如何读: T: Deref<Target = i32> “的任何T实现DerefTarget的的i32 ”。

You can then implement methods that dereference val : 然后,您可以实现取消引用val方法:

fn sum(&self) -> i32 {
    *self.val + self.other
}

In general, the concept of something like 一般而言,类似

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

Wouldn't prove useful. 不会证明有用。 Just because something is parameterized over a i32 doesn't mean you can do anything with that i32 . 仅仅因为在i32上进行了参数i32并不意味着您可以使用该i32 任何事情。 Likewise, a type could be parameterized with something besides an i32 (or not at all) and still give you access to an i32 . 同样,可以使用i32以外的i32 (或根本不使用)对类型进行参数化,并且仍然可以访问i32

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM