gpt4 book ai didi

Rust 函数指针逆变

转载 作者:行者123 更新时间:2023-12-03 11:27:27 26 4
gpt4 key购买 nike

我无法理解 Rust 中的逆变。

具体来说:

However, the same logic does not apply to arguments. Consider tryingto satisfy:

fn handle_animal(Animal);

with

fn handle_animal(Cat);

The first function can accept Dogs, but the second function absolutelycan't. Covariance doesn't work here. But if we flip it around, itactually does work! If we need a function that can handle Cats, afunction that can handle any Animal will surely work fine. Or torelate it back to real Rust: if we need a function that can handleanything that lives for at least 'long, it's perfectly fine for it tobe able to handle anything that lives for at least 'short.

(来自:https://doc.rust-lang.org/nomicon/subtyping.html)

这是我无法理解的部分:

Or to relate it back to real Rust: if we need a function that canhandle anything that lives for at least 'long, it's perfectly finefor it to be able to handle anything that lives for at least 'short.

如果你在需要“长”的地方传递“短”,这会不会不起作用,这意味着“传入的短”不会存在足够长的时间?

我知道当谈到生命周期时,如果 'long: 'short,那么 'long 是 'short 的子类型(如 'long'short 和更多),即使考虑到这一点,我仍然在为上述问题而苦苦挣扎..

谁能帮我理解一下?

此外,当谈到方差时,为什么我们说“over”,如:&mut T is invariant over T'

最佳答案

Wouldn't that not work as if you pass 'short somewhere where it needs 'long, it would mean that the 'short being passed in would not live long enough?

相反。我们在需要 'short 的地方传递了一个 'long,这行得通。

分解报价:

if we need a function that can handle anything that lives for at least 'long

我们需要一个可以接受 'long 的函数,这意味着我们必须要将 'long(或什至更长)传递给它。

it's perfectly fine for it to be able to handle anything that lives for at least 'short

所以,我们有一个 'long 作为参数传递,还有一个提供的函数接受 'short。没关系。该函数需要它至少存在 '短,它确实存在,因为它至少存在 '长

关于Rust 函数指针逆变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66020394/

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