我不太了解这个特性,它可以将元组 struct 强制转换为函数,如下所示:
struct MyType(u8);
let optional_mytype: Option<MyType> = Some(12).map(MyType);
// ^^^^^^ here, MyType is treated as a function
在上面的例子中,不涉及生命周期:一切都很简单.然而,当 struct 有一个通用的生命周期界限时,我很难定义它将强制执行的函数的确切签名.
以下是我try 做的一些事情的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<'_>`
我真的不明白为什么我的构造函数类型别名无效,为什么错误消息建议的类型比它应该的宽松得多.我的意思是,我的 struct 的生命周期<'a>
应该与 struct 中包含的单元引用的生命周期<'a>
完全相等,而不是随机的.
如果有上下文帮助的话,Here是一个更具体(仍然很小)的例子,说明我实际上在try 做什么.
提前谢谢