generics - 为多种类型实现泛型
问题描述
我想写一些如下代码:
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++ 的专业化。那么,我该如何实现呢?
解决方案
正如您所说的那样,您可以使用不稳定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
}
}
推荐阅读
- php - 使用自定义参数导出数据 Laravel Excel
- css - 如何在 Laravel 表单组中调整列宽
- javascript - 如何将类的实例添加到数组中的项目?
- postgresql - 在奇怪的条件下递归查询很慢
- c - 如果结构值位于 c 中另一个结构数组中的结构数组中,您将如何访问它们?
- reactjs - 尝试使用反应在表中查找检查值的总和
- r - 使用 heatmaply 创建带有原始值/数据而不进行转换的热图?
- python - 有没有办法直接从 python 中的二进制文件加载变量?
- java - 在 RESTful API 中创建和验证实体模型及其 DTO 的正确方法是什么?
- excel - 将时间范围分成每行半小时