Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should lifetime parameters be declared before type parameters?

Tags:

rust

lifetime

I was trying out a simple function when I got this compiler error. What is the actual reason behind this? In my case (following code), writing the type parameter before the lifetime parameter has no effect. Shouldn't the compiler know better?

use std::fmt::Debug;

fn random_func<T : Debug, 'a>(parameter : &'a mut T) {
    println!("{:?}", parameter);
}

fn main(){
    let mut name : String = "random".to_string();
    random_func(&mut name);
    println!("{:?}", "compiled successfully");
}

error:

life_time_trait.rs:3:27: 3:29 error: lifetime parameters must be declared prior to type parameters
life_time_trait.rs:3 fn random_func<T : Debug, 'a>(parameter : &'a mut T) {

                                           ^~
like image 237
basic_bgnr Avatar asked Apr 14 '26 22:04

basic_bgnr


1 Answers

I'm not sure this is the reason, but remember that type parameters can have lifetime bounds, but lifetime parameters can't have type bounds. So putting them first means you don't need to deal with non-forward declarations.

Personally, I think this rule makes things a bit easier to understand, and a bit easier to implement. Win-win!

like image 179
Steve Klabnik Avatar answered Apr 19 '26 04:04

Steve Klabnik



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!