Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the brackets before a function in Rust?

Tags:

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
like image 517
aug2uag Avatar asked Jul 24 '26 08:07

aug2uag


1 Answers

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.

like image 60
Sébastien Renauld Avatar answered Jul 28 '26 04:07

Sébastien Renauld



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!