如何制作具有特征的泛型的通用?

问题描述 投票:2回答:1
pub struct Triangle<T: Float + std::clone::Clone, V: vector::Vector<T>> {
    point1: V,
    point2: V,
    point3: V,
}

这段代码无法编译,因为未使用IT(尽管如此,T稍后会在方法中使用)

我试过这个语法

pub struct Triangle<V: vector::Vector<T: Float + std::clone::Clone>> {
    point1: V,
    point2: V,
    point3: V,
}

错误:

expected one of `!`, `(`, `+`, `,`, `::`, `<`, or `>`, found `:`

expected one of 7 possible tokens here

和这个语法

pub struct Triangle2<V> where V: vector::Vector<T> where T: Float {
    point1: V,
    point2: V,
    point3: V,
}

错误:

expected `where`, or `{` after struct name, found keyword `where`

expected `where`, or `{` after struct name

这不起作用。

他们是解决这个问题的方法吗?

rust
1个回答
4
投票

我假设您的类型Vector看起来或多或少像这样。

pub trait Vector<T> {
    // Some functions
}

解决方案是声明多个泛型类型并单独列出它们的类型约束:类型V必须实现Vector<T>并且类型T依次必须实现FloatClone

pub struct Triangle<V, T>
where
    V: vector::Vector<T>,
    T: Float + Clone,
{
    point1: V,
    point2: V,
    point3: V,
    phantom: PhantomData<T>,
}

我正在使用std::marker::PhantomData来保存其他未使用的类型信息。

Link to full working code

© www.soinside.com 2019 - 2024. All rights reserved.