Rust 中的本地函数 [英] A local function in Rust

查看:45
本文介绍了Rust 中的本地函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rust 中有任何方法可以创建一个 本地 函数,该函数可以多次调用.我在 Python 中这样做的方式是:

In there any way in Rust to create a local function which can be called more than once. The way I'd do that in Python is:

def method1():
  def inner_method1():
    print("Hello")

  inner_method1()
  inner_method1()

推荐答案

是的,你可以在函数内部定义函数:

Yes, you can define functions inside functions:

fn method1() {
    fn inner_method1() {
        println!("Hello");
    }

    inner_method1();
    inner_method1();
}

然而,内部函数无法访问外部作用域.它们只是不能从函数外部访问的普通函数.但是,您可以将变量作为参数传递给函数.要定义一个具有特定签名的函数,该函数仍然可以从外部作用域访问变量,您必须使用闭包.

However, inner functions don't have access to the outer scope. They're just normal functions that are not accessible from outside the function. You could, however, pass the variables to the function as arguments. To define a function with a particular signature that can still access variables from the outer scope, you must use closures.

这篇关于Rust 中的本地函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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