为什么使用f32 :: consts :: E会给出错误E0223,而std :: f32 :: consts :: E却没有?

时间:2019-01-30 21:30:40

标签: compiler-errors rust traits

如果我写:

let x = f32::consts::E;

我得到了错误:

error[E0223]: ambiguous associated type
  --> src/main.rs:32:21
   |
32 |             let x = f32::consts::E;
   |                     ^^^^^^^^^^^^^^ help: use fully-qualified syntax: `<f32 as Trait>::consts`

但是如果我改写:

let x = std::f32::consts::E;

然后一切都很好。该错误消息令人困惑,因为据我了解,f32是特定的具体类型而不是特征。我不确定为什么要使用某些特殊的特征语法。

编译器认为我在做什么?为什么我的修复程序有帮助?

1 个答案:

答案 0 :(得分:4)

  

编译器认为我在做什么

有一个名为 contacts.forEach(contact => { records.push(contact); }); 模块和一个名为f32 type 。默认情况下,该类型在任何地方都可用,而模块则不可用。

在没有其他导入的情况下,编译器最好将f32理解为类型f32::foo关联类型,但是没有这种类型。它假定关联的类型来自某个特征,并且建议您更清楚地了解它是什么特征。

执行f32时,路径会将模块带入范围,然后可以找到嵌套模块std::f32。您也可以这样做:

consts

任何类型都可能发生这种情况,但是通常类型和模块使用不同的命名方式(use std::f32; let x = f32::consts::E; UpperCamelCase):

snake_case
struct my_type;

mod other {
    pub mod my_type {
        pub mod consts {
            pub const ZERO: i32 = 0;
        }
    }
}

fn example() {
    my_type::consts::ZERO;
}

碰巧原始元素全部使用小写。

下面是一些(具有可疑用途)的代码,这些代码显示了关联类型实际上是如何发生的:

error[E0223]: ambiguous associated type
  --> src/lib.rs:12:5
   |
12 |     my_type::consts::ZERO;
   |     ^^^^^^^^^^^^^^^^^^^^^ help: use fully-qualified syntax: `<my_type as Trait>::consts`
相关问题