gpt4 book ai didi

rust - 匿名切片生命周期

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

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





Why can I return a reference to a local literal but not a variable?

(1 个回答)


1年前关闭。




考虑以下代码:

fn fun() {
let mut vec = vec![];
{
let x: &[u8] = &[1, 2];
vec.push(x); // why is the compiler happy?

let y = [3, 4];
let z: &[u8] = &y;
vec.push(z); // ok compiler is not happy
}

println!("{:?}", vec); // after commenting this line the compiler is happy again
}
我明白为什么编译器会提示 "borrowed value does not live long enough"对于 y但是为什么对 x 感到满意? ? x是对没有名称的切片的引用——这个匿名切片何时被删除,它的生命周期是多少?
评论后 println一切都会编译,我猜这是因为编译器理解 vec不在任何地方使用,所以它不在乎。

最佳答案

x 的情况下,编译器的原因是 &[1,2]借用了一个可以写成常数的表达式,所以constant promotion&'static [u8; 2] :

Promotion of a value expression to a 'static slot occurs when the expression could be written in a constant, borrowed, and dereferencing that borrow where the expression was originally written, without changing the runtime behavior. That is, the promoted expression can be evaluated at compile-time and the resulting value does not contain interior mutability or destructors (these properties are determined based on the value where possible, e.g. &None always has the type &'static Option<_>, as it contains nothing disallowed).

z 的表达式,即 &y ,不能写成常数,因为是借用了变量 y , 所以同样不适用于 z .

关于rust - 匿名切片生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64395683/

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