问题
In type hints in Rust it is possible to use partial types in annotations like this:
let myvec: Vec<_> = vec![1, 2, 3];
What is the correct terminology for the underscore in the partial type annotation? I'm interested in both the Rust terminology as well as more academic type theory terminology.
回答1:
I was able to find a piece of official documentation where the underscore is named in the context of patterns, but I doubt it's a "strict" name:
Patterns consist of some combination of literals, destructured arrays or enum constructors, structs and tuples, variable binding specifications, wildcards (..), and placeholders (_).
The Book provides the following description in the glossary:
_: "ignored" pattern binding (see Patterns (Ignoring bindings)). Also used to make integer-literals readable (see Reference (Integer literals)).
I was not able to find a definition pointing specifically to partial type annotations, but I think "placeholder" (or "type placeholder", depending on the context) would not be ambiguous.
回答2:
After some digging it seems that Vec<_>
is consistently called a partial type (so in let x: Vec<_>
we have a partial type annotation, while Fn(String) -> _
would be a partial type signature) but the _
in this context is varyingly called either a type wildcard or a type placeholder, and _
in the type grammar can be read as the token for "infer this type" (at the time of the PR mentioned below, TyInfer
internally in the compiler).
Some interesting reading:
- Partial type signatures in Haskell
- The pull request which added _ to the Rust type grammar
- Intermingled parameter lists - Niko Matsakis' blog post in which he proposes to "Introduce
_
as a notation for an unspecified lifetime or type"
Interesting detail from the PR:
let x: _ = 5;
let x = 5;
The two lines above are equivalent, and both parsed as variable x
with type TyInfer
.
回答3:
In the compiler, it seems to be called Infer
(in syntax::ast, rustc::hir, and rustc::ty)
I think this naming is somewhat reasonable, because these _
s are replaced with fresh (type) inference variables before doing Hindley-Milner-like type inference.
来源:https://stackoverflow.com/questions/45033804/what-is-the-correct-term-for-in-a-type-hint