Summary
A “sub function” that behaves just like a normal function but it has access to everything that was declared before it in the caller.
Motivation
Often I find myself wanting to divide up a function to organize code better and/or to have parts in different files. The current ways (that I know of) to do this is either to create a Struct containg the data or to include all the data I need as arguments. Which can be tedious if theres a lot and if you want to do this multiple times, and it kinda clutters the code.
Explanation
I think the easiest way to explain is with examples:
Note: I made up the keyword “sb” here to describe the new function type, but feel free to suggest a different keyword or maybe syntax for this.
Note: Examples here a simple, the meaning behind this is to use it with many variables and bigger code.
In this example the “sub function” (for my lack of coming up with a better name) Automaticly has access to the variable named value in the caller function without the developer having to pass it as a argument.
fn calc() {
let value = 100;
increment();
println!("{}", value); // 101;
}
sb increment() {
value += 1;
}
The “sub function” behaves like a normal function that it can also have arguments and returns.
fn calc() {
let value = 100;
let i = add(100);
println!("{}", value); // 200;
println!("{}", i); // 10;
}
sb add(x : u32) -> u32 {
value += x;
return 10;
}
And will shadow.
fn calc() {
let value = 100;
increment();
println!("{}", value); // 100;
}
sb increment() {
let value = 0; // the value in calc() gets shadowed by local variable
value += 1;
// local value dies here
}
Potential Issues:
- Multiple calls to the “sub function” and variables declared in between:
fn calc() {
let value = 100;
increment();
let other_value = 2;
increment();
}
sb increment() {
value += 1;
other_value += 1; // Error, needs to be declared before the first call
}
- Should a “sub function” be limited to only one caller?
fn calc() {
let value = 100;
increment();
}
fn calc2() {
let value = 10;
increment(); // Possible, because it has declared value, but there could be a rule that says "sb increment" can only
// belong to one function
}
sb increment() {
value += 1;
}
This could also open up a special name scheme (example syntax):
fn calc() {
let value = 100;
increment();
}
sb calc::increment() {
value += 1;
}