【问题标题】:What is type ascription?什么是类型归属?
【发布时间】:2016-04-03 19:17:24
【问题描述】:

我多次使用了错误的语法,比如在这个例子中忘记使用let

let closure_annotated = |value: i32| -> i32 {
    temp: i32 = fun(5i32);
    temp + value + 1
};
error[E0658]: type ascription is experimental (see issue #23416)
 --> src/main.rs:3:9
  |
3 |         temp: i32 = fun(5i32);
  |         ^^^^^^^^^

我知道这个问题是用let解决的,但是什么是“类型归属”,它有什么用呢?

我找到了issue #23416the feature gate for type ascription,但我不明白什么是“类型归属”或它的用途。

【问题讨论】:

    标签: syntax rust ascription


    【解决方案1】:

    类型归属是用我们希望它具有的类型注释表达式的能力。 Rust 中的类型归属在 RFC 803 中描述。

    在某些情况下,表达式的类型可能不明确。例如这段代码:

    fn main() {
        println!("{:?}", "hello".chars().collect());
    }
    

    给出以下错误:

    error[E0283]: type annotations required: cannot resolve `_: std::iter::FromIterator<char>`
     --> src/main.rs:2:38
      |
    2 |     println!("{:?}", "hello".chars().collect());
      |                                      ^^^^^^^
    

    这是因为 collect 方法可以返回任何实现迭代器 Item 类型的 FromIterator 特征的类型。有了类型归属,可以这样写:

    #![feature(type_ascription)]
    
    fn main() {
        println!("{:?}", "hello".chars().collect(): Vec<char>);
    }
    

    而不是当前(从 Rust 1.33 开始)消除此表达式歧义的方法:

    fn main() {
        println!("{:?}", "hello".chars().collect::<Vec<char>>());
    }
    

    或:

    fn main() {
        let vec: Vec<char> = "hello".chars().collect();
        println!("{:?}", vec);
    }
    

    【讨论】:

    • 一个更更好的例子是Into;因为类型参数里面有一个trait的参数,所以不可能注释一个.into()方法调用来指定类型。您必须重写表达式以改用带注释的函数调用。
    • That's because the collect method can return any type that implements the FromIterator -- 但为什么它会返回“chars()”类型以外的任何内容?
    • 您可以使用FromIterator将迭代器的剩余项收集到VecBTreeSetBinaryHeap等中。如果生成的集合是通用的,它的项类型通常会遵循迭代器的输出类型。 FromIterator 的某些实现仅适用于某些类型的迭代器,例如String 实现 FromIterator 仅用于 char 迭代器和 &amp;str 迭代器。
    • @felix [-1i32, 0, 1]
    • @felix 请ask new questions(您的评论中有两个独立的问题),cmets 不是用来提问和回答问题的。此外,由于整数默认为i32,因此缺少一块拼图,因此编译器推断u32这一事实意味着它从其他地方得到提示,它们应该改为u32
    猜你喜欢
    • 2011-01-06
    • 1970-01-01
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 2015-08-28
    • 1970-01-01
    • 2021-01-07
    相关资源
    最近更新 更多