fn() ->-6ren">
gpt4 book ai didi

rust - 语法问题函数返回函数不清楚

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

我对此感到困惑。
如果以下工作:

fn func_exit() -> bool {
println!("hi");
true
}

fn locate_func() -> fn() -> bool {
func_exit
}

为什么以下这些语法会引发错误?
fn locate_func1<F: Fn() -> bool>() -> F {
func_exit
}
fn locate_func2<F>() -> F where F:Fn() -> bool {
func_exit
}

我是 Rust 新手,我不清楚以下错误消息:
error[E0308]: mismatched types
--> src/main.rs:44:9
|
43 | fn locate_func1<F: Fn() -> bool>() -> F {
| - this type parameter - expected `F` because of return type
44 | func_exit
| ^^^^^^^^^ expected type parameter `F`, found fn item
|
= note: expected type parameter `F`
found fn item `fn() -> bool {func_exit}`
= help: type parameters must be constrained to match other types
= note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

error[E0308]: mismatched types
--> src/main.rs:47:9
|
46 | fn locate_func2<F>() -> F where F:Fn() -> bool {
| - - expected `F` because of return type
| |
| this type parameter
47 | func_exit
| ^^^^^^^^^ expected type parameter `F`, found fn item
|
= note: expected type parameter `F`
found fn item `fn() -> bool {func_exit}`
= help: type parameters must be constrained to match other types
= note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

感谢一些帮助。
谢谢

最佳答案

fn locate_func() -> fn() -> bool {
func_exit
}
locate_func返回指向返回 bool 的函数的指针(即 fn() -> bool )。
fn locate_func1<F: Fn() -> bool>() -> F {
func_exit
}
locate_func1表示调用者可以指定任何 F满足界限 Fn() -> bool ,它将返回 F .但是, func_exit 显然不是这样的。必须是调用者指定的类型。
locate_func2有同样的问题,只是 where -符号。

您可能想要的可能是以下内容:
fn locate_func3() -> impl Fn() -> bool {
func_exit
}

它说: locate_func3返回实现绑定(bind) Fn() -> bool 的内容(并且 func_exit 这样做了,所以它可以在那里返回)。

还要注意 fn 之间的区别(函数指针)和 Fn (“可调用的东西”):

关于rust - 语法问题函数返回函数不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61094966/

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