LVB*_*LVB 0 contravariance rust
在Nomicon的有关子类型的部分中,它说函数变量类型可以使用逆方差。但是,我找不到任何很好的例子。我试图用一个函数指针编码一个结构,但是矛盾似乎不起作用。
这是什么代码示例?
在您链接的页面上搜索“ 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;
}
Run Code Online (Sandbox Code Playgroud)
逆变例如不允许替换'static为'short:
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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
该协例如不允许替换'short为'static:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |