gpt4 book ai didi

rust - 生命周期参数和函数指针的问题

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

考虑这段代码:

struct WithLifetime<'a> {
s: &'a str
}

impl WithLifetime<'_> {
fn in_impl(&self) -> bool {
self.s == "a"
}
}

fn out_of_impl(wl: &WithLifetime<'_>) -> bool {
wl.s == "a"
}

fn higher_order(f: fn(&WithLifetime<'_>) -> bool) -> bool {
let s = "a";
let wl = WithLifetime { s };
f(&wl)
}

fn main() {
higher_order(out_of_impl); // This line compiles
higher_order(WithLifetime::in_impl); // This line does not
}

main 的最后一行编译失败并出现此错误:

error[E0308]: mismatched types
--> src/main.rs:23:18
|
23 | higher_order(WithLifetime::in_impl); // This line does not
| ^^^^^^^^^^^^^^^^^^^^^ one type is more general than the other
|
= note: expected fn pointer `for<'r, 's> fn(&'r WithLifetime<'s>) -> _`
found fn pointer `for<'r> fn(&'r WithLifetime<'_>) -> _`

据我所知,in_implout_of_impl 应该是完全相同的函数。它们都采用对 WithLifetime 的引用,并且不关心该引用的生命周期或 WithLifetime 实例的生命周期参数。两者都应该是传递给 higher_order 的有效参数。编译器不同意。

in_impl 传递给 higher_order 有什么问题,为什么编译器不允许这样做?如何将具有生命周期参数的结构上的结构方法传递给高阶函数?

最佳答案

首先,让我们找出所有 3 个函数的类型:

fn main() {
let x: i32 = out_of_impl;
let x: i32 = WithLifetime::in_impl;
let x: i32 = higher_order;
}

Playground

out_of_impl 的类型:

for<'r, 's> fn(&'r WithLifetime<'s>) -> bool {out_of_impl}

WithLifetime::in_impl 的类型:

for<'r> fn(&'r WithLifetime<'_>) -> bool {WithLifetime::<'_>::in_impl}

higher_order 的类型:

fn(for<'r, 's> fn(&'r WithLifetime<'s>) -> bool) -> bool {higher_order}

higher_order接受一个函数,在调用该函数之前,两个生命周期都不会被命名。所以它基本上接受一个适用于任何生命周期的函数'r's . out_of_impl满足该条件。

但在 WithLifetime::in_impl 的情况下,内部生命周期需要事先知道for<'r> fn(&'r WithLifetime<'_>) .

通过WithLifetime::in_impl ,您需要将其更改为:

fn in_impl<'b, 'c>(abc: &'b WithLifetime<'c>) -> bool {
abc.s == "a"
}

Playground

现在,这个函数适用于任意生命周期 'b'c .


接受in_impl不改变它,如@Milan做了,

fn higher_order<'b>(f: fn(&WithLifetime<'b>) -> bool) -> bool {
let s = "a";
let wl = WithLifetime { s };
f(&wl)
}

Playground

现在,higher_order有一个类型:

for<'b> fn(for<'r> fn(&'r WithLifetime<'b>) -> bool) -> bool {higher_order}

它接受一个生命周期为'r的函数仅在函数被调用和liftime 'b 时定义事先已知。

这适用于 out_of_impl因为它接受任意的生命周期。也适用于 in_impl因为现在签名匹配 higher_order .

How does for<> syntax differ from a regular lifetime bound?对 HRTB 有一个很好的解释。

关于rust - 生命周期参数和函数指针的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65117383/

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