gpt4 book ai didi

rust - 具有父类(super class)型生命周期的引用不能用于子类型生命周期

转载 作者:行者123 更新时间:2023-11-29 08:18:13 24 4
gpt4 key购买 nike

我正在努力理解生命周期的子类型化是如何工作的。 subtype 这个名字让我觉得如果 'b'a 的子类型,那么 'a 类型的东西> 可以用在任何类型 'b 将被使用的地方。实际上,在生命周期的背景下,我看不出允许这样做会出什么问题。但是,下面的代码

fn test<'a, 'b: 'a>(first: &'a mut str, second: &'b mut str) -> &'b str {
// do something to choose between the two arguments,
// eventually pick first on some branch
first
}

不起作用,因为“这两种类型声明为具有不同的生命周期......但是来自 first 的数据在这里流入 second。”

那么如果允许这样做会出什么问题呢?

最佳答案

So what would go wrong if this was allowed?

在这个例子中你的推理是颠倒的:约束 'b: 'a 读作 "'b 一样长作为 'a"。由于 test 的输出需要生存至少,只要生命周期 'b'a 仍然代表一个可能不兼容的生命周期,first 实际上可能活得不够长。

如果你翻转生命周期,代码就会编译。

fn test<'a, 'b: 'a>(first: &'b mut str, second: &'a mut str) -> &'a str {
first
}

关于rust - 具有父类(super class)型生命周期的引用不能用于子类型生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53971157/

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