Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Types 使用where子句实现Trait:实现一个简单的where子句_Types_Rust_Traits - Fatal编程技术网

Types 使用where子句实现Trait:实现一个简单的where子句

Types 使用where子句实现Trait:实现一个简单的where子句,types,rust,traits,Types,Rust,Traits,我一直试图通过学习生锈,但却遇到了一堵具有以下特征的墙: // There is an alternate syntax for placing trait bounds on a function, the // where clause. Let's revisit a previous example, this time using 'where'. #[test] fn where_clause() { let num_one: u16 = 3; let num_two

我一直试图通过学习生锈,但却遇到了一堵具有以下特征的墙:

// There is an alternate syntax for placing trait bounds on a function, the
// where clause. Let's revisit a previous example, this time using 'where'.
#[test]
fn where_clause() {
    let num_one: u16 = 3;
    let num_two: u16 = 4;

    trait IsEvenOrOdd {
        fn is_even(&self) -> bool;
    }

    impl IsEvenOrOdd for u16 {
        fn is_even(&self) -> bool {
            self % 2 == 0
        }
    }

    fn asserts<T>(x: T, y: T) {
        assert!(!x.is_even());
        assert!(y.is_even());
    }

    asserts(num_one, num_two);
}
仍然-代码没有编译。似乎由于
T
被解引用,我需要为解引用的值添加边界,但我找不到任何示例来说明如何执行此操作

error[E0369]:二进制操作“%”不能应用于类型“%T”`
-->src\koans/traits.rs:142:13
|
142 |自我%2==0
|             ^^^^^^^^
|
=注意:`&T可能缺少`std::ops::Rem`的实现`

简而言之:解决这个koan的惯用方法是什么?

我想你可能误解了这个练习的意图。你想要的是:

fn main() {
    let num_one: u16 = 3;
    let num_two: u16 = 4;

    trait IsEvenOrOdd {
        fn is_even(&self) -> bool;
    }

    impl IsEvenOrOdd for u16 {
        fn is_even(&self) -> bool {
            self % 2 == 0
        }
    }

    fn asserts<T>(x: T, y: T)
        where T: IsEvenOrOdd {
        assert!(!x.is_even());
        assert!(y.is_even());
    }

    asserts(num_one, num_two);
}

此错误告诉我们,要调用
is_even
方法,必须实现
IsEvenOrOdd
。您发布的示例顶部的注释表示在函数上使用
where
子句。将
where
子句添加到函数
断言
可以解决问题并完成练习

“目标似乎是通过创建IsEvenOrOdd实现的通用版本来完成这段代码。”是吗?我假设目标只是添加一个
where
子句,以便代码能够编译;要解决koan,请将
中的T:IsEvenOrOdd
添加到
fn断言中
fn main() {
    let num_one: u16 = 3;
    let num_two: u16 = 4;

    trait IsEvenOrOdd {
        fn is_even(&self) -> bool;
    }

    impl IsEvenOrOdd for u16 {
        fn is_even(&self) -> bool {
            self % 2 == 0
        }
    }

    fn asserts<T>(x: T, y: T)
        where T: IsEvenOrOdd {
        assert!(!x.is_even());
        assert!(y.is_even());
    }

    asserts(num_one, num_two);
}