小编JON*_*vas的帖子

使用函数指针时,"预期的fn项,找到了不同的fn项"

我有以下代码(游乐场):

// Two dummy functions, both with the signature `fn(u32) -> bool`
fn foo(x: u32) -> bool {
    x % 2 == 0
}
fn bar(x: u32) -> bool {
    x == 27
}


fn call_both<F>(a: F, b: F)
where
    F: Fn(u32) -> bool,
{
    a(5);
    b(5);
}

fn main() {
    call_both(foo, bar);  // <-- error
}
Run Code Online (Sandbox Code Playgroud)

对我来说,它看起来这应该是编译foobar具有相同的签名:fn(u32) -> bool.然而,我收到以下错误:

error[E0308]: mismatched types
  --> src/main.rs:20:20
   |
20 |     call_both(foo, bar);
   |                    ^^^ …
Run Code Online (Sandbox Code Playgroud)

rust

9
推荐指数
2
解决办法
990
查看次数

枚举错误:未解析的名称

在同一文件中定义的枚举构造函数不再解析.

enum Mode {
    Global,
    Local,
}

fn which_mode() -> Mode {
    Global
}

fn main() {
    match which_mode() {
        Global => println!("Global"),
        Local  => println!("Local"),
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器Global在函数中给出错误"未解析的名称" which_mode.当我将其限定为合格时Mode::Global,它就有效.现在,它认为,Globalmatch语句是有约束力的,并因此无可辩驳!

这种行为是最近的 - 11月11日晚上成功编译了上面的代码.按照目前的行为是怎么回事,为什么Some,Ok,不需要限定路径?

enums rust

5
推荐指数
1
解决办法
1579
查看次数

Rust函数返回一个闭包:``需要显式生命周期绑定"

以下代码无法编译.

fn main() {
    let foo = bar(8);

    println!("Trying `foo` with 4: {:d}", foo(4));
    println!("Trying `foo` with 8: {:d}", foo(8));
    println!("Trying `foo` with 13: {:d}", foo(13));
}

//

fn bar(x: int) -> (|int| -> int) {
    |n: int| -> int {
        if n < x { return n }

        x
    }
}
Run Code Online (Sandbox Code Playgroud)

错误如下.

11:32 error: explicit lifetime bound required
.../hello/src/main.rs:11 fn bar(x: int) -> (|int| -> int) {
                                            ^~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

bar通过值传递整数参数.为什么Rust关心值传递的整数的生命周期?编写返回闭包的函数的正确方法是什么?谢谢.

编辑

我在手册中找到了以下内容. In the simplest and least-expensive form …

rust

4
推荐指数
2
解决办法
2381
查看次数

未装箱的瓶盖类型各不相同

这是在错误消息与未装箱的闭包的问题的上下文中。答案指出,Rust 生成每个闭包都唯一的类型,因为每个闭包都可能从封闭范围捕获一组不同的变量。

这是我的问题。FizzBu​​zz 示例中的两种不同的闭包类型标记不同,但看起来相同。编译器如何解决闭包类型差异,同时仍然查看类型参数的相同签名?

编译器看到的内容和程序员看到的内容之间的差距令人困惑。

谢谢。

编辑:顺便说一句,Rust 参考文档第 8.1.10 节尚未对此做出任何说明。

rust

1
推荐指数
1
解决办法
1009
查看次数

标签 统计

rust ×4

enums ×1