aug2uag
aug2uag

Reputation: 3445

What are the brackets before a function in Rust?

What is the purpose of the brackets in function declarations. For instance what's the difference between the following:

/// without brackets
pub fn new_with_now(now: T) -> SomeType

/// with brackets
pub fn new_with_now<T: Now>(now: T) -> SomeType

Upvotes: 7

Views: 4835

Answers (1)

S&#233;bastien Renauld
S&#233;bastien Renauld

Reputation: 19672

The answer is in the doc: Generics

A type parameter is specified as generic by the use of angle brackets and upper camel case: . "Generic type parameters" are typically represented as . In Rust, "generic" also describes anything that accepts one or more generic type parameters . Any type specified as a generic type parameter is generic, and everything else is concrete (non-generic).

Your second definition is a type restriction to T requiring an implementation of Now (whatever that may be). In turn, below the hood, the compiler will generate a variant of new_with_now for every struct used that implements Now and calls this function at any given point.

Upvotes: 11

Related Questions