Rust中逆向使用的一个例子是什么?

时间:2019-03-25 19:09:31

标签: rust contravariance

Nomicon's section about subtyping中,它表示可用于函数指针类型的逆方差。但是,我找不到任何很好的例子。我试图用一个函数指针编码一个结构,但是矛盾似乎不起作用。

这是什么代码示例?

1 个答案:

答案 0 :(得分:5)

Rust's notion of subtyping only applies to lifetimes.


the page you linked上搜索“ contra”一词有很多相关段落:

  

实际上,在Rust中,目睹自相矛盾是非常困难的,尽管它确实存在。

  

注意:语言中唯一的矛盾源是函数的参数,这就是为什么它实际上在实践中并没有太多应用的原因。调用协方差涉及使用函数指针进行高阶编程,这些函数指针采用具有特定生存期的引用(与通常的“任何生存期”相对,后者进入较高的生存期,而该生存期与子类型无关)。

  

这就是为什么函数类型与语言中的其他函数不同,因此它们的参数相反的原因。

该页面以所有逆类型的示例结尾。正在应用...

Contravariance

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