gpt4 book ai didi

rust - 无法返回对临时数组的静态引用,即使该数组包含也具有静态生命周期的值

转载 作者:行者123 更新时间:2023-11-29 08:07:19 24 4
gpt4 key购买 nike

T::bar 返回的值具有 'static 生命周期,因此 Test2::foo 范围不需要拥有任何事物。返回 &[T::bar()] 作为 &'static [&'static StructType] 应该是安全的? Test:foo 编译没有问题,所以我期待 Test2::foo 也可以编译。

代码

pub struct StructType {
a: &'static str,
}

pub trait Foo {
fn foo() -> &'static [&'static StructType];
fn bar() -> &'static StructType;
}

pub struct Test;

impl Foo for Test {
fn foo() -> &'static [&'static StructType] {
&[&StructType { a: "asdf" }]
}

fn bar() -> &'static StructType {
&StructType { a: "asdf" }
}
}

pub struct Test2<T: Foo>(T);

impl<T: Foo> Test2<T> {
pub fn foo() -> &'static [&'static StructType] {
&[T::bar()]
}
}

playground

错误

error[E0515]: cannot return reference to temporary value
--> src/lib.rs:26:9
|
26 | &[T::bar()]
| ^----------
| ||
| |temporary value created here
| returns a reference to data owned by the current function

最佳答案

RFC that added the automatic promotion of references to values to 'static状态:

Promote constexpr rvalues to values in static memory instead of stack slots, and expose those in the language by being able to directly create 'static references to them.

文字值是最明显的常量表达式。但是,函数调用不是常量,除非使用const 明确标记为常量。然而,从 Rust 1.31 开始,用户定义的 const 函数中可用的操作类型相当有限。允许使用文字值:

const fn bar() -> &'static StructType {
&StructType("asdf")
}

const fn combo() -> &'static [&'static StructType; 1] {
&[Self::bar()]
}

还不允许const 函数中将对数组的引用转换为切片,因此需要在不同的函数中:

fn wombo() -> &'static [&'static StructType] {
Self::combo()
}

此外,您不能在特征中定义 const 函数。

另见:

What I really need are 1) have T::bar() return a constant, 2) have Test:foo return an array constant, that is constructed from T::bar() and U::bar() and U, T are generic parameter to Test

你不能这样做

fn example<T>() {
static NO_CAN_DO: T = unimplemented!();
}
error[E0401]: can't use type parameters from outer function
--> src/lib.rs:2:23
|
1 | fn example<T>() {
| ------- - type variable from outer function
| |
| try adding a local type parameter in this method instead
2 | static NO_CAN_DO: T = unimplemented!();
| ^ use of type variable from outer function

另见:

关于rust - 无法返回对临时数组的静态引用,即使该数组包含也具有静态生命周期的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53907854/

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