我可以使用方法或函数作为闭包吗? [英] Can I use a method or a function as a closure?

查看:44
本文介绍了我可以使用方法或函数作为闭包吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在结构上有一些方法,我想将它们作为参数传递.我很确定传递函数的唯一方法是使用闭包.有没有办法我可以不用做<代码>||{ self.x() }?

I have some methods on a struct that I'd like to pass around as parameters. I'm pretty sure the only way to pass around functions is by using closures. Is there a way I can do this without doing || { self.x() }?

推荐答案

您绝对可以将方法或函数用作闭包.您使用函数或方法的完整路径,包括特征方法:

You can absolutely use a method or a function as a closure. You use the full path to the function or method, including trait methods:

免费功能:

struct Monster {
    health: u8,
}

fn just_enough_attack(m: Monster) -> u8 {
    m.health + 2
}

fn main() {
    let sully = Some(Monster { health: 42 });
    let health = sully.map(just_enough_attack);
}

固有方法:

struct Monster {
    health: u8,
}

impl Monster {
    fn health(&self) -> u8 { self.health }
}

fn main() {
    let sully = Some(Monster { health: 42 });
    let health = sully.as_ref().map(Monster::health);
}

特征方法:

fn main() {
    let name = Some("hello");
    let owned_name = name.map(ToOwned::to_owned);
}

请注意,参数类型必须完全匹配,包括按引用或按值.

Note that the argument type must match exactly, this includes by-reference or by-value.

这篇关于我可以使用方法或函数作为闭包吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆