Reputation: 34884
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()
Upvotes: 83
Views: 33616
Reputation: 131
This is an old question, but I came to it from Jon Gjengset's excellent Rust for Rustaceans, which notes an interesting use case for inner functions Rust. Namely, if you have a function which is generic, but which has non-generic sub-components, you can write an inner function to reduce the amount of machine code duplication produced by monomorphization. He gives the example of HashMap::insert
, which of course has to compute a hash for some generic type K
, but under some implementations walking the map to find the insertion point might be non-generic.
Happy coding!
Upvotes: 10
Reputation: 65782
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.
Upvotes: 129