What is type ascription?

后端 未结 1 1913
一整个雨季
一整个雨季 2020-12-09 16:00

Several times I\'ve used the wrong syntax, such as forgetting to use let in this example:

let closure_annotated = |value: i32| -> i32 {
    t         


        
相关标签:
1条回答
  • 2020-12-09 16:11

    Type ascription is the ability to annotate an expression with the type we want it to have. Type ascription in Rust is described in RFC 803.

    In some situations, the type of an expression can be ambiguous. For example, this code:

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

    gives the following error:

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

    That's because the collect method can return any type that implements the FromIterator trait for the iterator's Item type. With type ascription, one could write:

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

    Instead of the current (as of Rust 1.33) ways of disambiguating this expression:

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

    or:

    fn main() {
        let vec: Vec<char> = "hello".chars().collect();
        println!("{:?}", vec);
    }
    
    0 讨论(0)
提交回复
热议问题