【发布时间】:2019-03-25 19:09:31
【问题描述】:
在Nomicon's section about subtyping 中,它说逆变可用于函数指针类型。但是,我找不到任何好的例子。我试图用函数指针编写一个结构,但逆变似乎不起作用。
这是什么代码示例?
【问题讨论】:
标签: rust contravariance
在Nomicon's section about subtyping 中,它说逆变可用于函数指针类型。但是,我找不到任何好的例子。我试图用函数指针编写一个结构,但逆变似乎不起作用。
这是什么代码示例?
【问题讨论】:
标签: rust contravariance
Rust's notion of subtyping only applies to lifetimes.
在the page you linked 上搜索“contra”一词有许多相关段落:
实际上在 Rust 中见证逆变是相当困难的,尽管它确实存在。
注意:语言中逆变的唯一来源是函数的参数,这就是为什么它在实践中并没有出现太多的原因。调用逆变涉及使用具有特定生命周期的引用的函数指针的高阶编程(与通常的“任何生命周期”相反,它进入更高等级的生命周期,独立于子类型工作)。
这就是为什么函数类型与语言中的其他任何东西不同,它们的参数是逆变的。
页面以所有逆变类型的示例结束。应用它...
struct MyContraType<Mixed> {
k1: fn(Mixed), // contravariant over Mixed
}
fn contra_example<'short>(
mut a: MyContraType<&'short u8>,
mut b: MyContraType<&'static u8>,
x: fn(&'short u8),
y: fn(&'static u8),
) {
a.k1 = x;
a.k1 = y; // Fails
b.k1 = x;
b.k1 = y;
}
逆变示例不允许用'static 代替'short:
error[E0308]: mismatched types
--> src/lib.rs:12:12
|
12 | a.k1 = y;
| ^ lifetime mismatch
|
= note: expected type `fn(&'short u8)`
found type `fn(&'static u8)`
note: the lifetime 'short as defined on the function body at 5:19...
--> src/lib.rs:5:19
|
5 | fn contra_example<'short>(
| ^^^^^^
= note: ...does not necessarily outlive the static lifetime
struct MyCoType<Mixed> {
k1: fn() -> Mixed, // covariant over Mixed
}
fn co_example<'short>(
mut a: MyCoType<&'short u8>,
mut b: MyCoType<&'static u8>,
x: fn() -> &'short u8,
y: fn() -> &'static u8,
) {
a.k1 = x;
a.k1 = y;
b.k1 = x; // Fails
b.k1 = y;
}
协变示例不允许将'short 替换为'static:
error[E0308]: mismatched types
--> src/lib.rs:29:12
|
29 | b.k1 = x;
| ^ lifetime mismatch
|
= note: expected type `fn() -> &'static u8`
found type `fn() -> &'short u8`
note: the lifetime 'short as defined on the function body at 21:15...
--> src/lib.rs:21:15
|
21 | fn co_example<'short>(
| ^^^^^^
= note: ...does not necessarily outlive the static lifetime
【讨论】: