什么是类型归属? [英] What is type ascription?
问题描述
我多次使用错误的语法,例如在这个例子中忘记使用 let
:
letclosure_annotated = |值:i32|->i32 {温度:i32 = 乐趣(5i32);温度 + 值 + 1};
<块引用>
error[E0658]: type ascription is Experimental (see issue #23416)-->src/main.rs:3:9|3 |温度:i32 = 乐趣(5i32);|^^^^^^^^^^
我知道使用let
可以解决这个问题,但是什么是类型归属",它的用途是什么?
我发现了 issue #23416 和 类型归属的特征门,但我不能了解类型归属"是什么或其目的是什么.
类型归属是使用我们希望表达式具有的类型来注释表达式的能力.Rust 中的类型归属在 RFC 803一>.
在某些情况下,表达式的类型可能不明确.例如,这段代码:
fn main() {println!("{:?}", "hello".chars().collect());}
给出以下错误:
error[E0283]:需要类型注释:无法解析`_: std::iter::FromIterator<char>`-->src/main.rs:2:38|2 |println!("{:?}", "hello".chars().collect());|^^^^^^^^
那是因为 collect
方法可以返回任何实现 的类型FromIterator
迭代器的 Item
类型的特征.使用类型归属,可以这样写:
#![feature(type_ascription)]fn 主(){println!("{:?}", "hello".chars().collect(): Vec);}
代替当前(从 Rust 1.33 开始)消除此表达式歧义的方法:
fn main() {println!("{:?}", "hello".chars().collect::>());}
或:
fn main() {let vec: Vec= "你好".chars().collect();println!("{:?}", vec);}
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.
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);
}
这篇关于什么是类型归属?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!