Rust闭包如何获取String类型参数并返回值?

时间:2016-10-06 21:56:15

标签: rust closures

在Rust中,如果我返回一个如此定义的闭包:

fn closure_thing() (Fn(String) -> String) {
    |thing| {
        thing[1..4]
    }
}

我收到错误:

= note: `std::ops::Fn(std::string::String) -> std::string::String + 'static` does not have a constant size known at compile-time
= note: the return type of a function must have a statically known size`

我试过Fn(& String) - > & String也是如此。是否有一种简单的方法让闭包将字符串作为参数并返回一个字符串?

2 个答案:

答案 0 :(得分:3)

Fn是一个特质。你不能回归特质。您可以返回一个函数指针:

fn closure_thing() -> (fn(String) -> String) {
    fn foo(thing: String) -> String {
        …
    }

    foo
}

您还可以返回Box

fn closure_thing() -> Box<Fn(String) -> String> {
    Box::new(|thing| {
        …
    })
}

但是那个有运行时成本,因此应该被视为最后的手段。

如@Veedrac所述,您也可以使用impl Trait

#![feature(conservative_impl_trait)]

fn closure_thing() -> impl Fn(String) -> String {
    |thing| {
        …
    }
}

但是从Rust 1.12开始,这还不稳定,需要夜间编译器。它允许您返回任何特征,而无需先前解决方案的运行时成本。

答案 1 :(得分:2)

  

函数的返回类型必须具有静态已知大小

实现这一目标的一种方法是封闭封闭......

fn closure_thing() -> Box<Fn(String) -> String> {
    Box::new(|thing| {
        (&thing[1..4]).to_string()
    })
}

请注意,我还将结果转换为String ..因为切片会返回str

正如mcarton所述,装箱将导致堆分配的运行时成本。

相关问题