January 2019
Beginner to intermediate
554 pages
13h 31m
English
Apart from using traits to constrain the types that can be accepted by a generic function, we can also constrain generic type parameters using lifetime annotations. For instance, consider we have a logger library where the Logger object is defined as follows:
// lifetime_bounds.rsenum Level { Error}struct Logger<'a>(&'a str, Level);fn configure_logger<T>(_t: T) where T: Send + 'static { // configure the logger here}fn main() { let name = "Global"; let log1 = Logger(name, Level::Error); configure_logger(log1);}
In the preceding code, we have a Logger struct with its name and a Level enum. We also have a generic function called configure_logger that takes a type T that is constrained with Send + 'static ...
Read now
Unlock full access