代码之家  ›  专栏  ›  技术社区  ›  Joseph Garvin

为什么使用f32::consts::E会出现错误E0223,而std::f32::consts::E不会出现错误?

  •  0
  • Joseph Garvin  · 技术社区  · 7 年前

    如果我写:

    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 是一种特定的具体类型,而不是一种特征。我不知道为什么我会使用一些特殊的trait语法。

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

    1 回复  |  直到 7 年前
        1
  •  4
  •   Shepmaster Tim Diekmann    7 年前

    编译器认为我在做什么

    有一个 打电话 f32 还有一个 打电话 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`
    

    原语恰好使用所有小写字母。

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

    struct Consts;
    
    impl Consts {
        const E: char = 'e';
    }
    
    trait Example {
        type consts;
    }
    
    impl Example for f32 {
        type consts = Consts;
    }
    
    fn example() {
        <f32 as Example>::consts::E;
    }