Why i need parameters if i can declare variable on the body of function?

We can define functions to have parameters, which are special variables that are part of a function’s signature. - The book

In The Book about function parameter, there's sample code when i pass value to main and other function parameter for storing integer & variable names.


fn main() {
another_function(2000);
}

fn another_function(two_thousand: i32){
println!("My monthly income is {two_thousand}$");
}

Just curious about parameter () on the function. So is there's any example when we must use parameter rather than putting variable or anything on the body function.

Thank you.

In the code above, a parameter is not passed "to main" as you said. It is passed from main to another_function.

By "parameter ()" are you referring to the fact that the main function has no parameters?

I don't know what you mean by "putting variable or anything on the body function" -- can you show the line of code you're referring to?

My question is about parameter use case. In The Book is like building a variable in the parameter and match it.

I can make variable and store some value on the body of main function, i dont need parameter. When i should use parameter? is there any example?

fn main() {
two_thousand:i32 = 2000;
println!("My monthly income is {two_thousand}$");
p
}

Functions have parameters so that they can be told to do something different when they are called from different places or different times.

In a program this small, there is no need to have any functions but main(), so there is no need for parameters. In more complex programs, functions are absolutely essential — programs would be huge if you couldn't reuse code to do more than one job and build up complex programs out of small, separable parts.

3 Likes

Oh, you're asking why do we need functions with parameters. Right?

Is this your first programming language? If so, Rust is not a good choice. Rust is a relatively complex language, and the Rust book does not explain beginning concepts like function parameters.

Thank you, got it :grin:

Yay, you're right. This is my first lang. I have another learn option too, but i like this stuff. I cant stop learn when 1st time read the book :smile:.

1 Like

As an aside, there have been other threads with some suggestions for those who are new to programming (along side lots of conversation about how suitable Rust is or isn't as a first language -- which there is no consensus on). For example, and another, and surely others if you search.

2 Likes

Well thank you :smile: