Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Rust type alias need a lifetime parameter?

I tried the following Rust type alias:

type Name = String;

It works fine. So I tried a variant:

type Name = &str;

This failed with:

error[E0106]: missing lifetime specifier
 --> src/main.rs:1:17
  |
1 |     type Name = &str;
  |                 ^ expected lifetime parameter

Why would a type alias need a lifetime parameter and how would I add it?


1 Answers

The problem is String owns its memory, while &str is a reference to a str. Usually you can elide lifetimes, but when a reference is stored in a struct, enum, or type alias, all lifetimes must be specified. So the correct way to write the alias is:

type Name<'a> = &'a str;

The lifetime is declared after the name of the type alias, and the lifetime of &str is specified to be 'a.

Lifetimes on types can be elided in functions sometimes, which is why you can write &str. This also applies to other types, including type aliases. That means this is valid:

fn foo(s: &String) -> Name { s.as_str() }

The lifetime parameter on Name is elided here.

like image 106
pengowen123 Avatar answered Jun 25 '26 22:06

pengowen123



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!