什么是类型归属?
What is type ascription?
有好几次我使用了错误的语法,例如在这个例子中忘记使用 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
可以解决这个问题,但是"type ascription"是什么,有什么用呢?
我找到了 issue #23416 and the feature gate for type ascription,但我不明白 "type ascription" 是什么或它的用途是什么。
类型归属是用我们想要的类型来注释表达式的能力。 RFC 803.
中描述了 Rust 中的类型归属
在某些情况下,表达式的类型可能不明确。例如,这段代码:
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());
| ^^^^^^^
那是因为迭代器的 Item
类型的 collect
method can return any type that implements the 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);
}
有好几次我使用了错误的语法,例如在这个例子中忘记使用 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
可以解决这个问题,但是"type ascription"是什么,有什么用呢?
我找到了 issue #23416 and the feature gate for type ascription,但我不明白 "type ascription" 是什么或它的用途是什么。
类型归属是用我们想要的类型来注释表达式的能力。 RFC 803.
中描述了 Rust 中的类型归属在某些情况下,表达式的类型可能不明确。例如,这段代码:
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());
| ^^^^^^^
那是因为迭代器的 Item
类型的 collect
method can return any type that implements the 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);
}