将 const 关联到 Rust 中的特征,但未按照本教程中的描述工作

Associated const to a trait in Rust not working as described in the tutorial

我正在尝试执行所描述的相同代码 here

(第~448页)

Playground

但是当我尝试执行这个示例时,我得到:

error[E0038]: the trait `Float` cannot be made into an object


--> src\main.rs:35:25
   |
35 |     let fibonacci_of_3: dyn Float = fibonacci(3);
   |                         ^^^^^^^^^ `Float` cannot be made into an object
   |
   = help: consider moving `ZERO` to another trait
   = help: consider moving `ONE` to another trait
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
  --> src\maths.rs:4:11
   |
3  | pub trait Float {
   |           ----- this trait cannot be made into an object...
4  |     const ZERO: Self;
   |           ^^^^ ...because it contains this associated `const`
5  |     const ONE: Self;
   |           ^^^ ...because it contains this associated `const`

这是斐波那契函数:

pub fn fibonacci<T: Float + Add<Output=T>>(n: usize) -> T {
    match n {
        0 => T::ZERO,
        1 => T::ONE,
        n => fibonacci::<T>(n - 1) + fibonacci::<T>(n - 2),
    }
}

关于动态,没有它我得到:

error[E0782]: trait objects must include the `dyn` keyword
  --> src\main.rs:34:25
   |
34 |     let fibonacci_of_3: Float = fibonacci(3);
   |                         ^^^^^
   |
help: add `dyn` keyword before this trait
   |
34 |     let fibonacci_of_3: dyn Float = fibonacci(3);
   |                         +++

是信息过时了还是我做错了什么?,理论上说得通。

此致

~M

您需要指定您要使用的类型(不是特征本身):

use std::ops::Add;

trait Float {
    const ZERO: Self;
    const ONE: Self;
}

impl Float for f32 {
    const ZERO: f32 = 0.0;
    const ONE: f32 = 1.0;
}

impl Float for f64 {
    const ZERO: f64 = 0.0;
    const ONE: f64 = 1.0;
}

fn fibonacci<T: Float + Add<Output=T>>(n: usize) -> T {
    match n {
        0 => T::ZERO,
        1 => T::ONE,
        n => fibonacci::<T>(n - 1) + fibonacci::<T>(n - 2),
    }
}

fn main() {
   let fibonacci_of_3: f32 = fibonacci::<f32>(3);
}

Playground

请注意,您不能使用 dyn Float。编译器不知道如何为该特征构建 vtable,因为它根本没有任何方法。