Rust for the Novice Programmer/Functions
Functions
[edit | edit source]Let's say we wanted to do the x2 + 5 again but to y with a starting value of 7. What would that look like?
fn main() {
let mut x = 10;
x *= x;
x += 5;
println!("{}", x);
let mut y = 7;
y *= y;
y += 5;
println!("{}", y);
}
This will work, but say we wanted to change it to x2 + 8 for both of them. This means we would have to change it in both locations. This doesn't seem like too much effort here, but these patterns of wanting to do the same things, just with slightly different values is very common. Therefore we can separate this out into a function. Let's take one of them first:
fn print_value() {
let mut x = 10;
x *= x;
x += 5;
println!("{}", x);
}
This will work, except the point of a function is to take in input(s) that can have different values. The way to put an input into a function is to put it inside the () brackets. You put the name of the input, similar to the name of a variable, then you have to explicitly write out the type of the input.
fn calc_value(input: i32) {
let mut value = input;
value *= value;
value += 5;
println!("{}", value);
}
Note that we set value to the value of input. This means since we use the 'mut' keyword, we can modify the value inside the function. Alternatively we could put mut before 'input' and then input would be modifiable. Next we can change main() to
fn main() {
calc_value(10);
calc_value(7);
}
This means the code is a lot easier to modify and separate out, making it easier to read and edit later.
An alternative way might be if we wanted to not print out inside the function and instead output the different value, so that the main() function can print it out or do anything it wants with it. This is called returning and you specify the return value with '-> type'. For example, the function will return an integer, so we return i32 by adding '-> i32' after the () but before the {}.
fn calc_value(input: i32) -> i32 {
let mut value = input;
value *= value;
value += 5;
return value;
}
Then we print the values in the main() function as so:
fn main() {
let value1 = calc_value(10);
let value2 = calc_value(7);
println!("{}", value1);
println!("{}", value2);
}
This lets us do more interesting things, like chaining function calls together. For example we can change the main to:
fn main() {
let mut value = calc_value(10);
value = calc_value(value);
println!("{}", value);
}
This does the x2 + 5 on 10 twice, so we get 11030. This has just been a rough overview of functions and their usefulness.