Reputation: 55
How is it that I am allowed to do this?
fn procedure(param: f64) {
println!("{}", param + 9);
But not allowed to do this without declaring mutable on the parameter?
fn procedure(mut param: f64) {
param += 9.;
println!("{}", param);
Is it because in the second function I act directly on the variable itself?
I'm trying to learn Ownership in Rust and I'm confused as to what is considered "mutating". Is there different rules for doing actions on variables that fill curly braces in print macros? In my main function:
procedure(param_in_main);
println!("printing {} in main", param_in_main);
Both of the functions will give the same result without altering the passed variable. The video I am following as a guide places significance on mutability not altering the variable passed in main. But it didn't alter it to begin with in the first procedure. I think I am just misunderstanding what is being said but any feedback in regards to memory/copies in this case would be great.
Upvotes: 0
Views: 1234
Reputation: 2533
Mutating is about modifying an already defined value. Arguments are named and already defined when the function is called. Same when you define your own variables.
You code
fn procedure(param: f64) {
println!("{}", param + 9);
is conceptually the same as
fn procedure(param: f64) {
println!("{}", {let a0 = param + 9; a0});
Meaning that a temporary variable is created that stores the value of param + 9
and then passed as argument to println
. You're not mutating anything, you are just creating a new temporary variable.
Upvotes: 1