小编The*_*son的帖子

我可以有可选的特征界限吗?

给定一个模拟条件概率分布的特征:

trait Distribution {
    type T;
    fn sample<U>(&self, x: U) -> Self::T;
}
Run Code Online (Sandbox Code Playgroud)

我想实现两个结构的特征,ConditionalNormal分别MultivariateConditionalNormal对标量和向量值分布进行建模。

这样的实现看起来像这样:

struct ConditionalNormal;

impl Distribution for ConditionalNormal {
    type T = f64;

    fn sample<U>(&self, x: U) -> Self::T {
        0.0
    }
}

struct MultivariateConditionalNormal;

impl Distribution for MultivariateConditionalNormal {
    type T = f64;

    fn sample<U>(&self, x: U) -> Self::T {
        0.0 + x[0]
    }
}
Run Code Online (Sandbox Code Playgroud)

游乐场

然而, 的实现MultivariateConditionalNormal是无效的,因为泛型x[0]不可索引。如果我添加特征边界,std::ops::Index<usize>则实现ConditionalNormal无效,因为标量f64不可索引。

我听说,例如,该Sized …

generics rust

4
推荐指数
1
解决办法
652
查看次数

我如何接受可以通过`..`切割的任意容器?

我有以下简单的设置:

pub trait Distribution {
    type T;
    fn sample(&self) -> Self::T;
}

pub fn foo<D, U>(dist: &D, f: &Fn(&[f64]))
where
    D: Distribution<T = U>,
    U: std::ops::Index<usize>,
{
    let s = dist.sample();
    f(&s[..]);
}
Run Code Online (Sandbox Code Playgroud)

foo接受了实现通用容器Distribution和功能,但如果我用它像一个例子这样:

struct Normal {}

impl Distribution for Normal {
    type T = Vec<f64>;
    fn sample(&self) -> Self::T {
        vec![0.0]
    }
}

fn main() {
    let x = Normal {};
    let f = |_x: &[f64]| {};
    foo(&x, &f);
}
Run Code Online (Sandbox Code Playgroud)

它不起作用,因为f(&s[..]);它不是切片类型:

error[E0308]: …
Run Code Online (Sandbox Code Playgroud)

rust

2
推荐指数
1
解决办法
107
查看次数

标签 统计

rust ×2

generics ×1