A local function in Rust

戏子无情 提交于 2020-12-04 14:33:30

问题


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()

回答1:


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.



来源:https://stackoverflow.com/questions/26685666/a-local-function-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!