[英]Associated const to a trait in Rust not working as described in the tutorial
我正在尝试执行与此处描述的相同的代码
(第~448页)
但是当我尝试执行这个示例时,我得到:
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`
这是斐波那契 function:
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),
}
}
关于 dyn,没有它我得到:
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);
}
请注意,您不能使用dyn Float
。 编译器不知道如何为该特征构建 vtable,因为它根本没有任何方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.