相关疑难解决方法(0)

如何在泛型函数中要求泛型类型实现Add,Sub,Mul或Div等操作?

我正在尝试在Rust中实现泛型函数,其中对参数的唯一要求是应该定义乘法运算.我正在尝试实现一个通用的"权力",但将使用更简单的cube功能来说明问题:

use std::ops::Mul;

fn cube<T: Mul>(x: T) -> T {
    x * x * x
}

fn main() {
    println!("5^3 = {}", cube(5));
}
Run Code Online (Sandbox Code Playgroud)

编译时我收到此错误:

error[E0369]: binary operation `*` cannot be applied to type `<T as std::ops::Mul>::Output`
 --> src/main.rs:4:5
  |
4 |     x * x * x
  |     ^^^^^^^^^
  |
  = note: an implementation of `std::ops::Mul` might be missing for `<T as std::ops::Mul>::Output`
Run Code Online (Sandbox Code Playgroud)

这是什么意思?我选择了错误的特质吗?我该如何解决这个问题?

generics rust

21
推荐指数
2
解决办法
3128
查看次数

使用泛型类型时如何使用整数文字?

我想实现一个函数来计算任何泛型类型的整数中的位数.这是我提出的代码:

extern crate num;
use num::Integer;

fn int_length<T: Integer>(mut x: T) -> u8 {
    if x == 0 {
        return 1;
    }

    let mut length = 0u8;
    if x < 0 {
        length += 1;
        x = -x;
    }

    while x > 0 {
        x /= 10;
        length += 1;
    }

    length
}

fn main() {
    println!("{}", int_length(45));
    println!("{}", int_length(-45));
}
Run Code Online (Sandbox Code Playgroud)

这是编译器输出

error[E0308]: mismatched types
 --> src/main.rs:5:13
  |
5 |     if x == 0 {
  |             ^ expected type parameter, …
Run Code Online (Sandbox Code Playgroud)

generics int traits rust

7
推荐指数
2
解决办法
1905
查看次数

在 Rust 中,如何限制泛型 T 以允许模数?

作为锻炼练习,我目前正在尝试根据值是否为偶数来过滤迭代器,以生成新的迭代器。

我的功能目前看起来像:

pub fn evens<T>(iter: impl Iterator<Item = T>) -> impl Iterator<Item = T>
    where T: std::ops::Rem<Output = T>
{
    iter.filter(|x| x % 2 != 0)
}
Run Code Online (Sandbox Code Playgroud)

操场

但这不会编译,因为:

pub fn evens<T>(iter: impl Iterator<Item = T>) -> impl Iterator<Item = T>
    where T: std::ops::Rem<Output = T>
{
    iter.filter(|x| x % 2 != 0)
}
Run Code Online (Sandbox Code Playgroud)

但是,我知道我不能简单地将其更改为

error[E0369]: cannot mod `&T` by `{integer}`
 --> src/lib.rs:4:23
  |
4 |     iter.filter(|x| x % 2 != 0)
  |                     - ^ - {integer}
  | …
Run Code Online (Sandbox Code Playgroud)

restriction modulo bounds type-parameter rust

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

在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
查看次数