Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

rust - Lifetime bound of the form T: 'a

I am trying to understand what T: 'a means, where, I guess, T is a type and 'a is a lifetime.

I understand what 'a: 'b means: x('a) outlives y('b) and so we cannot assign y to x in the following code

fn foo<'a, 'b, T>(mut x: &'a T, mut y: &'b T) 
   where 'a: 'b {
  x = y; //compile time error
}

This reference book writes

T: 'a means that all lifetime parameters of T outlive 'a.

But I am confused by the "all lifetime parameters of T". What is a "lifetime parameter of (type?) T" ? I know that 'a is a lifetime of x in this signature fn foo<'a, T>(x: &'a T). Does it mean the same thing?

Could someone explain what T:'a means by giving an example? I can't even imagine where we could use it and why.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While references can have lifetimes, types can have lifetimes too. The simplest example would probably be:

struct Foo<'a> {
    x: &'a i32
}

If you construct a struct of type Foo (let's call this instance foo) with a reference to an i32 (let's call this num) on the local stack, then foo cannot live longer than the scope of num, regardless of the scope of foo itself. It's a lifetime without a reference (to the type, at least).

Let's take a look at a real world example of this: Box::leak:

pub fn leak<'a>(b: Box<T>) -> &'a mut T
where
    T: 'a,

The type signature basically says that, given a box, you can create a reference to its value for any lifetime as long as the value itself is capable of lasting for that lifetime. So, we could create a &'static i32 with Box::leak, since i32 has nothing restricting its lifetime, but we can't create a &'static Foo that references a stack integer, as it has a reference restricting its lifetime.

Note that if you're testing this locally, things like &5 will actually create a &'static i32 due to rvalue static promotion, so you might want to change the i32 to an unpromotable type like String.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...