[英]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.