Generics 我可以有可选的特征边界吗?
给定模拟条件概率分布的特征:Generics 我可以有可选的特征边界吗?,generics,rust,Generics,Rust,给定模拟条件概率分布的特征: trait Distribution { type T; fn sample<U>(&self, x: U) -> Self::T; } () 但是,MultivariateConditionalNormal的实现无效,因为泛型x[0]不可索引。 如果我添加trait boundsstd::ops::Index,ConditionalNormal的实现无效,因为标量f64是不可索引的 我听说,例如,size特征通过?siz
trait Distribution {
type T;
fn sample<U>(&self, x: U) -> Self::T;
}
()
但是,MultivariateConditionalNormal
的实现无效,因为泛型x[0]
不可索引。
如果我添加trait boundsstd::ops::Index
,ConditionalNormal
的实现无效,因为标量f64
是不可索引的
我听说,例如,
size
特征通过?size
接受可选的特征边界;我可以做类似的事情吗?有没有办法解决这个问题?您可以将特征的定义更改为
trait Distribution<U> {
type T;
fn sample(&self, x: U) -> Self::T;
}
性状分布{
T型;
fn样本(&self,x:U)->self::T;
}
这允许您在具有不同特征边界的各种类型上实现它
impl<U> Distribution<U> for ConditionalNormal {
// ...
}
impl<U> Distribution<U> for MultivariateConditionalNormal
where
U: std::ops::Index<usize, Output = f64>,
{
// ...
}
条件正态分布的impl分布{
// ...
}
多变量条件正态分布的impl分布
哪里
U:std::ops::索引,
{
// ...
}
您可以添加一个新特性来指定
U
的功能:
trait Distribution {
type T;
fn sample<U>(&self, x: U) -> Self::T
where
U: Samplable;
}
struct ConditionalNormal;
impl Distribution for ConditionalNormal {
type T = f64;
fn sample<U>(&self, x: U) -> Self::T
where
U: Samplable,
{
0.0.value()
}
}
struct MultivariateConditionalNormal;
impl Distribution for MultivariateConditionalNormal {
type T = f64;
fn sample<U>(&self, x: U) -> Self::T
where
U: Samplable,
{
0.0 + x.value()
}
}
trait Samplable {
fn value(&self) -> f64;
}
impl Samplable for f64 {
fn value(&self) -> f64 {
*self
}
}
impl Samplable for Vec<f64> {
fn value(&self) -> f64 {
self[0]
}
}
fn main() {}
性状分布{
T型;
fn样本(&self,x:U)->self::T
哪里
U:样本;
}
结构条件常态;
条件正态分布{
T型=f64;
fn样本(&self,x:U)->self::T
哪里
U:Samplable,
{
0.0.value()
}
}
结构多变量条件正态分布;
多变量条件正态分布的impl分布{
T型=f64;
fn样本(&self,x:U)->self::T
哪里
U:Samplable,
{
0.0+x.值()
}
}
特征样本{
fn值(&self)->f64;
}
f64的impl样本{
fn值(&self)->f64{
*自我
}
}
Vec的impl样本{
fn值(&self)->f64{
自我[0]
}
}
fn main(){}
谢谢您的回答。这是我想要的。谢谢我也喜欢这个解决方案!也许将来可以试试!谢谢@TheodorJohnson你必须在泛型中加入更多的语义。当您有一个泛型类型T
时,问自己一个问题:我将如何处理T
?并将这些操作作为一种新特性的方法。
trait Distribution {
type T;
fn sample<U>(&self, x: U) -> Self::T
where
U: Samplable;
}
struct ConditionalNormal;
impl Distribution for ConditionalNormal {
type T = f64;
fn sample<U>(&self, x: U) -> Self::T
where
U: Samplable,
{
0.0.value()
}
}
struct MultivariateConditionalNormal;
impl Distribution for MultivariateConditionalNormal {
type T = f64;
fn sample<U>(&self, x: U) -> Self::T
where
U: Samplable,
{
0.0 + x.value()
}
}
trait Samplable {
fn value(&self) -> f64;
}
impl Samplable for f64 {
fn value(&self) -> f64 {
*self
}
}
impl Samplable for Vec<f64> {
fn value(&self) -> f64 {
self[0]
}
}
fn main() {}