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

Traits with parameterized associated types

我有 C++ 背景,想知道我是否可以 code up a trait for use in the foo and bar functions:

#![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!");
}

foo 有效,但 bar 中的嵌套类型参数 rc_val 会导致问题:

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

我在 nightly 版本中看到了一些关于 this on the IRC channel related to Higher Kinded Types, but I'm not that familiar with functional programming. Can someone suggest a workaround for what I'm trying to do here? This code was tested in the playground 的信息。

设计的意思是you should be able to just write

fn bar<T: MyTrait>(rc_val: T::SB) {}

MyTrait 的特征实现 MyFoo 已经指定了 SB 的类型参数。

如果你想连接SBVAL,可以在SB上放置特征边界,例如:

trait MyTrait {
    type VAL;
    type SB: Deref<Target = Self::VAL>;
}