gpt4 book ai didi

rust - 元组结构到函数强制 : what are the lifetime parameters of said function?

转载 作者:行者123 更新时间:2023-12-05 05:42:19 24 4
gpt4 key购买 nike

我不了解可以将元组结构强制转换为函数的功能,如下所示:

struct MyType(u8);

let optional_mytype: Option<MyType> = Some(12).map(MyType);
// ^^^^^^ here, MyType is treated as a function

在上面的示例中,不涉及生命周期:一切都很简单。但是,当结构具有通用生命周期限制时,我在定义它将强制执行的函数的确切签名时遇到了麻烦。

这是我尝试做的事情的 MRE,但它不起作用(sandbox link):

struct MyStruct<'a>(&'a ());

// This looks, to me, like the signature the "constructor" should have
type MyStructConstructor = for<'a> fn(&'a ()) -> MyStruct<'a>;

/// Coercion problem here
fn some_code() {
let mut constructor: MyStructConstructor = MyStruct;
}

以及类型检查器给出的错误:

   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
--> src/lib.rs:7:48
|
7 | let mut constructor: MyStructConstructor = MyStruct;
| ^^^^^^^^ one type is more general than the other
|
= note: expected fn pointer `for<'a> fn(&'a ()) -> MyStruct<'a>`
found fn pointer `fn(&()) -> MyStruct<'_>`

老实说,我不明白为什么我的构造函数类型别名无效,以及为什么错误消息建议的类型比应有的松散得多。我的意思是,一生 <'a>我的结构应该与结构中包含的单元引用完全相同,而不是随机的。

Here这是我实际尝试做的更具体(仍然是最小的)示例,如果上下文对您有帮助的话。

提前致谢

最佳答案

事实上,错误信息可能有点误导。 '_并不意味着任何生命都过去了,它只是意味着我没有明确命名的生命,就像写&()一样(与 &'_ () 相同)。 Rust 这样做是因为那不是问题所在。

为了便于理解,让我们在您的代码中实际注释隐式泛型生命周期:

fn some_code() {
let constructor: MyStructConstructor = MyStruct<'_>;
}

请注意哪里出了问题?在右边,你有一些东西,它的类型在整个生命周期都是通用的。在左边,你没有。事实上,一个更合适的构造函数签名 MyStruct会是

struct MyStruct<'a>(&'a ());

type MyStructConstructor<'a> = fn(&'a ()) -> MyStruct<'a>;

fn some_code() {
let constructor: MyStructConstructor = MyStruct;
}

隐式保留生命周期 — 参见 the playground .这编译。

所以现在你可能明白为什么MyStructConstructorMyStruct 更通用:因为 MyStruct ,你必须指定生命周期开始,也就是说,实际类型是,对于给定的 'a , MyStruct<'a> .然后,使用该构造函数,您只能构建类型为 MyStruct<'a> 的对象。 , 给出 &'a () .另一方面,使用 MyStructConstructor , 给出了对 () 的引用在任何的生命周期中,你都可以构建一个MyStruct生命周期相同,更通用。

关于rust - 元组结构到函数强制 : what are the lifetime parameters of said function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72070519/

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