Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
839 views
in Technique[技术] by (71.8m points)

syntax - What is type ascription?

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

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);
  |         ^^^^^^^^^

I know that this problem is solved by using let, but what is "type ascription" and what is its use?

I found issue #23416 and the feature gate for type ascription, but I could not understand what "type ascription" is or what is its purpose.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...