What are the brackets before a function in Rust?

by aug2uag   Last Updated September 20, 2019 11:26 AM - source

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
Tags : rust

Answers 1

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.

Sébastien Renauld
Sébastien Renauld
September 20, 2019 11:25 AM

Related Questions

How to idiomatically alias a crate in Rust 2018?

Updated December 13, 2018 23:26 PM

What is Cargo.lock for in a rust library?

Updated September 11, 2019 19:26 PM