首页 > 解决方案 > 为多种类型实现泛型

问题描述

我想写一些如下代码:

use crate::{Ty1, Ty2};
struct Test<A, B> {
    ..
}
/// Match when A = Ty1 and B = Ty2
impl Test<Ty1, Ty2> {
    fn test() {
        ..
    }
}
/// Match all other cases
impl<?, ?> Test<?, ?> {
    fn test() {
        ..
    }
}

当然可以手动实现所有 4 种情况,但我不想这样做。据我所知,Rust 不支持类似 C++ 的专业化。那么,我该如何实现呢?

标签: genericsrust

解决方案


正如您所说的那样,您可以使用不稳定specialization的功能来做到这一点。

stable 的唯一选择是根本不使用泛型:

enum Ty {
  Ty1(Ty1),
  Ty2(Ty2),
}

struct Test {
  v1: Ty,
  v2: Ty,
}

impl Test {
  fn test(&self) {
    if let Ty1(v1) = self.v1 {
      if let Ty2(v2) = self.v2 {
        // specific logic
        return;
      }
    }
    // default logic
  }
}

推荐阅读