gpt4 book ai didi

indexing - 为什么需要引用索引?

转载 作者:行者123 更新时间:2023-12-03 11:25:35 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What is the return type of the indexing operation?

(2 个回答)


1年前关闭。




我目前正在学习来自 JavaScript 的 Rust。
我的问题如下:

fn main() {
let name = String::from("Tom");
let sliced = name[..2];
println!("{}, {}", name, sliced);
}
这行不通。说 "doesn't have a size known at compile-time" .
要解决此问题,我需要添加 &引用运算符。
fn main() {
let name = String::from("Tom");

let sliced = &name[..2];

println!("{}, {}", name, sliced);
}
我知道我需要添加 &在姓名和 & 之前是引用运算符。但我只是不知道为什么我真的需要这样做?
通过引用变量,引用引用变量 name但不拥有它。如果我的引用超出范围,原始值将不会被删除。这是否意味着如果我执行 name[...],变量会超出范围?并且变量被删除,因此我需要创建对它的引用以防止这种情况发生?
有人可以解释一下吗?

最佳答案

I know I need to add & before name and & is the referencing operator. But I just don't know why I actually need to do that.


我知道困惑来自哪里,因为当您查看 index() 时它返回 &Self::Output .所以它已经返回了一个引用,这是怎么回事?

这是因为索引运算符是语法糖并使用 Index 特征。然而,虽然它使用 index() 它确实返回了一个引用,这不是它被脱糖的方式。
总之 x[i] 未翻译成 x.index(i) , 但实际上到 *x.index(i) ,所以引用被立即取消引用。这就是你最终得到 str 的方式。而不是 &str .
let foo = "foo bar"[..3]; // str
// same as
let foo = *"foo bar".index(..3); // str
这就是为什么您需要添加 &让它“回到”引用。
let foo = &"foo bar"[..3]; // &str
// same as
let foo = &*"foo bar".index(..3); // &str
或者,如果您调用 index() 直接,那么它当然不会被隐式取消引用。
use std::ops::Index;

let foo = "foo bar".index(..3); // &str
Trait std::ops::Index - Rust Documentation :

container[index] is actually syntactic sugar for *container.index(index)


这同样适用于 IndexMut .

关于indexing - 为什么需要引用索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65212978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com