相关疑难解决方法(0)

如何实现参数化特征的特征

我有一个设计问题,当使用类似的东西时:

trait MyTrait<K: OtherTrait> { ... }

impl<K: OtherTrait, M: MyTrait<K>> AnyTrait for M { ... }
Run Code Online (Sandbox Code Playgroud)

由于E207错误("类型参数K不受impl trait,self type或谓词"约束),我无法为此特征实现特征.

找不到摆脱这个错误,我应用这个不那么好看的解决方法(详细和结构没有内在价值):

use std::fmt;
use std::marker::PhantomData;

pub trait MyTrait<K: fmt::Display> {
    fn get_some_k(&self) -> Option<K>;
}

/* // This is my target impl but results in E207 due to K not constrained
impl<K: fmt::Display, S: MyTrait<K>> fmt::Display for S {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.get_some_k().unwrap())
    }
} */
pub struct Ugly<'a, …
Run Code Online (Sandbox Code Playgroud)

traits rust

8
推荐指数
1
解决办法
1622
查看次数

使用泛型的特征的毯子实现

我正在通过实现矩阵数学来练习Rust,而且我遇到了一些障碍.我定义了我认为与矩阵相关的特征.

trait Matrix<T> where T : num::Num  {
    fn dim(&self) -> (usize, usize);
    fn elem(&self, i : usize, j : usize) -> Option<& T>; 
    fn new_const(v: T, rows : usize, cols : usize) -> Self where T : Clone;

    fn same_dim<U>(&self, other: &U) -> bool where U : Matrix<T> {
        self.dim() == other.dim()
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个愚蠢的实现使用Vec<Vec<T>>.我实现了所有方法并测试了它们.他们都在工作.现在我想简单地将两个矩阵一起添加.因此,如果不添加我知道将需要的行迭代器并执行我知道的添加实现将是不正确的,我将以下内容添加.

impl <T, U> Add for U where T: num::Num, U: Matrix<T> {
    type Output = U;

    fn add(self, _rhs: U) -> U …
Run Code Online (Sandbox Code Playgroud)

generics matrix rust

6
推荐指数
1
解决办法
316
查看次数

在Rust中实现通用的可递增特征

我试图了解如何在Rust中实现一般特征.

虽然我已经看过很多例子,但这些例子与特定用途(例如基因组变异器)过于紧密联系,因此我能够在Rust开发过程中理解这一点.

相反,这是一个基于相当普遍的东西的简单示例 - 递增:

trait Incrementable {
    fn post_inc(&mut self) -> Self;
    fn post_inc_by(&mut self, n: usize) -> Self;
}

impl Incrementable for usize {
    fn post_inc(&mut self) -> Self {
        let tmp = *self;
        *self += 1;
        tmp
    }

    //"Overload" for full generalizability
    fn post_inc_by(&mut self, n: usize) -> Self {
        let tmp = *self;
        *self += n;
        tmp
    }
}

fn main() {
    let mut result = 0;
    assert!(result.post_inc() == 0);
    assert!(result == 1);

    assert!(result.post_inc_by(3) …
Run Code Online (Sandbox Code Playgroud)

traits generic-programming rust

3
推荐指数
1
解决办法
439
查看次数

标签 统计

rust ×3

traits ×2

generic-programming ×1

generics ×1

matrix ×1