Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A local function in Rust

Tags:

rust

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() 
like image 418
Incerteza Avatar asked Nov 01 '14 02:11

Incerteza


People also ask

How do you call a function in Rust?

We define a function in Rust by entering fn followed by a function name and a set of parentheses. The curly brackets tell the compiler where the function body begins and ends. We can call any function we've defined by entering its name followed by a set of parentheses.

Where is the function in Rust?

Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code.

What does -> mean in Rust?

It means that we are allowed to write, for example: let x: i32 = if some_condition { 42 } else { panic!("`!` is coerced to `i32`") };

What are closures in Rust?

Rust's closures are anonymous functions you can save in a variable or pass as arguments to other functions. You can create the closure in one place and then call the closure elsewhere to evaluate it in a different context. Unlike functions, closures can capture values from the scope in which they're defined.


1 Answers

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.

like image 164
Francis Gagné Avatar answered Oct 05 '22 13:10

Francis Gagné