[英]How to make a generic of generic with trait?
pub struct Triangle<T: Float + std::clone::Clone, V: vector::Vector<T>> {
point1: V,
point2: V,
point3: V,
}
這段代碼無法編譯,因為未使用 T(盡管如此,稍后在方法中使用了 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
那行不通。
有沒有辦法解決這個問題?
我假設你的類型Vector
看起來或多或少像這樣。
pub trait Vector<T> {
// Some functions
}
解決方案是聲明多個泛型類型並分別列出它們的類型約束:類型V
必須實現Vector<T>
而類型T
又必須實現Float
和Clone
。
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來保存其他未使用的類型信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.