具有参数化关联类型的特征

Sim*_*mon 2 traits rust

我来自C++背景,并想知道我是否可以编写一个特性用于foobar函数:

#![feature(alloc)]

use std::rc::{Rc, Weak};

pub trait MyTrait {
    /// Value type
    type VAL;
    /// Strongly boxed type
    /// Will be constrained to something like Box, Rc, Arc
    type SB;
    /// Weakly boxed type
    type WB;
}

struct MyFoo;

impl MyTrait for MyFoo {
    type VAL = i64;
    type SB = Rc<i64>;
    type WB = Weak<i64>;
}

fn foo<T: MyTrait>(value: T::VAL) {}
// Uncomment
// fn bar<T: MyTrait>(rc_val: T::SB<T::VAL>) {}

fn main() {
    let x = 100 as i64;
    let y = Rc::new(200 as i64);
    foo::<MyFoo>(x);
    // Uncomment
    // bar::<MyFoo>(y);

    println!("Hello, world!");
}
Run Code Online (Sandbox Code Playgroud)

foo工作,但嵌套类型参数rc_valbar原因的问题:

error[E0109]: type parameters are not allowed on this type
  --> src/main.rs:25:34
   |
25 | fn bar<T: MyTrait>(rc_val: T::SB<T::VAL>) {}
   |                                  ^^^^^^ type parameter not allowed
Run Code Online (Sandbox Code Playgroud)

我在与高级类型相关的IRC频道上看到了一些关于此的内容,但我对函数式编程并不熟悉.有人可以建议我在这里尝试做什么吗?此代码在操场上使用构建进行了测试.nightly

huo*_*uon 5

设计意味着你应该能够写作

fn bar<T: MyTrait>(rc_val: T::SB) {}
Run Code Online (Sandbox Code Playgroud)

MyTraitfor 的trait实现MyFoo已经指定了type参数SB.

如果你要连接SBVAL,一个可以把特征范围上SB,例如:

trait MyTrait {
    type VAL;
    type SB: Deref<Target = Self::VAL>;
}
Run Code Online (Sandbox Code Playgroud)