Why use an immutable link to i32

There is an example in the Lifetime of the Rust book chapter:

struct Foo<'a> { x: &'a i32, } fn main() { let y = &5; // this is the same as `let _y = 5; let y = &_y;` let f = Foo { x: y }; println!("{}", fx); } 

Why do they use x: &'a i32 ?

I think that if it's just x: i32 , then they cannot demonstrate the use of life. However, is there another reason? Is there any production code that uses an immutable reference to a primitive type like i32?

+7
reference primitive-types rust
source share
1 answer

In this particular case, the reason is to really show the concept of lifetimes. As for the general case, however, I see no reason to make an invariable reference to a primitive type (mutable links, of course, is another matter), except when this is done in general code:

 struct Holder<'a, T> { r: &'a T } let x: i32 = 123; let h: Holder<i32> = Holder { r: &x }; 

Here, if you have such a structure, you have no other choice to use the link to i32 . Naturally, this structure can also be used with other, non-primitive and fixed types.

As Shepmaster mentioned in the comments, there really is a case where you have references to primitive types - these are iterators of links. Remember, by convention (which follows the standard library), the iter() method in the collection should return an iterator of links to the collection:

 let v: Vec<i32> = vec![1, 2, 3, 4]; let i = v.iter(); // i is Iterator<Item=&i32> 

Then almost all methods on the iterator that accept the closure will accept closures, the argument of which is a reference:

 i.map(|n| *n + 1) // n is of type &i32 

Note that this is actually the result of a more general case with generics. Vectors and slices can contain arbitrary types, including non-movable ones, so they just need to have methods that allow their users to borrow their contents.

+10
source share

All Articles