为什么使用对 i32 的不可变引用 [英] Why use an immutable reference to i32
问题描述
在 Rust 书的生命周期一章中,有一个例子:
In the chapter Lifetimes of the Rust book, there's an example:
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!("{}", f.x);
}
他们为什么使用 x: &'a i32
?
我认为如果它只是 x: i32
那么他们无法证明生命周期的使用情况.然而,这背后还有其他原因吗?是否有任何生产代码使用对像 i32 这样的原始类型的不可变引用?
I think if it is just x: i32
then they cannot demonstrate the lifetime usage. However, is there any other reason behind it? Is there any production code that uses immutable reference to a primitive type like i32?
推荐答案
在这种特殊情况下,原因确实是为了展示生命周期的概念.然而,对于一般情况,我认为没有理由对原始类型进行不可变引用(当然,可变引用是另一回事),除非它是在泛型代码中完成的:
In this particular case the reason is indeed to show the concept of lifetimes. As for the general case, however, I see no reason making an immutable reference to a primitive type (mutable references, of course, is another matter) except of when it is done in generic code:
struct Holder<'a, T> {
r: &'a T
}
let x: i32 = 123;
let h: Holder<i32> = Holder { r: &x };
在这里,如果您有这样的结构,您别无选择,只能使用对 i32
的引用.当然,这种结构也可以用于其他非原始和不可移动的类型.
Here if you have such structure, you have no other choice as to use a reference to an i32
. Naturally, this structure can also be used with other, non-primitive and non-movable types.
正如 Shepmaster 在评论中提到的,确实存在一种情况,您引用原始类型 - 它是按引用迭代器.请记住,根据约定(标准库遵循的约定),集合上的 iter()
方法应该将引用的迭代器返回到集合中:
As Shepmaster has mentioned in comments, there is indeed a case where you have references to primitive types - it is by-reference iterators. Remember, by a convention (which the standard library follows) iter()
method on a collection should return an iterator of references into 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 which take a closure will accept closures whose argument is a reference:
i.map(|n| *n + 1) // n is of type &i32
请注意,这实际上是泛型更一般情况的结果.向量和切片可能包含任意类型,包括不可移动的类型,因此它们只需要拥有允许用户借用其内容的方法.
Note that this is in fact a consequence of the more general case with generics. Vectors and slices may contain arbitrary types, including non-moveable ones, so they just have to have methods which would allow their users to borrow their contents.
这篇关于为什么使用对 i32 的不可变引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!