Erik Vesteraas
Erik Vesteraas

Reputation: 4735

What is the correct term for _ in a type hint?

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.

Upvotes: 12

Views: 2453

Answers (4)

solstice333
solstice333

Reputation: 3659

Seems like the grammar refers to it as an "inferred type". Per the documentation:

Inferred type

Syntax:

InferredType : _

The inferred type asks the compiler to infer the type if possible based on the surrounding information available. It cannot be used in item signatures. It is often used in generic arguments:

let x: Vec<_> = (0..10).collect();

Upvotes: 1

Erik Vesteraas
Erik Vesteraas

Reputation: 4735

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:

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.

Upvotes: 4

Masaki Hara
Masaki Hara

Reputation: 3545

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.

Upvotes: 2

ljedrz
ljedrz

Reputation: 22273

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.

Upvotes: 8

Related Questions