English 中文(简体)
为什么要你回头谈谈临时问题?
原标题:Why can t you return a reference to a temporary?
  • 时间:2024-01-01 02:34:43
  •  标签:
  • rust

为什么要你回头谈谈Rust的临时问题? 激励性的实例是:

fn what< cellref,  cell:  cellref>(x: &f64) -> & cellref CellValue< cell> {
    &CellValue::Number(*x)
}

人们可能认为,汇编者可以推断,只要参考文献存在,目标就需要活下来,这样就能够活下来,直到参考文献被删除。 为什么汇编者会忽略这一点?

问题回答

汇编者能否推断出这一点无关紧要,因为没有mechanism,汇编者可以据此满足这一要求。

认为Rustt公司拥有(built-in)的垃圾收集器,因此,汇编者只能发出指示,对肥皂分配大值,让GC予以照顾。 它需要某些地方储存至少可活到的手机/代码,但不会超出寿命的<代码>。 它无法构造这种地点;你必须提供这种地点(例如<代码>&x mut CellValue< cell> x: cellref)。 或者,你只能返回<代码>CellValue< cell>,而不是退回参考。

贵问题中的哪类守则可以用于纯粹不变的价值,因为汇编者does 具有确定这些价值的地点:它可将价值推入双亲的正文部分,并重新提及。 事实上,这恰恰是描述字面的发生。 这里的问题是,<代码>x不是汇编时常数,而是在操作时间之前不知道其参考资料的参考资料。 因此,汇编者不能建立<条码>静态例>。

违反这一法典,这实际上汇编了:

fn what(x: &f64) -> & static CellValue< static> {
    &CellValue::Number(&42.0)
}

环绕:leak acode>Box。 这里显而易见的是,留有<代码>CellValue的记忆被永久泄漏,在方案终止之前不能收回。

fn what< cell>(x: & cell f64) -> & cell CellValue< cell> {
    Box::leak(Box::new(CellValue::Number(x)))
}




相关问题
Creating an alias for a variable

I have the following code in Rust (which will not compile but illustrates what I am after). For readability purposes, I would like to refer the same string with two different names so that the name of ...

Rust Visual Studio Code code completion not working

I m trying to learn Rust and installed the Rust extension for VSCode. But I m not seeing auto-completions for any syntax. I d like to call .trim() on String but I get no completion for it. I read that ...

热门标签