MOCKSTACKS
EN
Questions And Answers

More Tutorials








RUST Function parameters

Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined.

There are 2 ways of passing parameters:
  • By value
  • By Reference

RUST Function parameter By Value

When passing value by value to a method original value wont change and the value will be only used inside that method. if any modification happen to the value inside the method it wont carry that value to where it was called from.

Example of passing parameter by value in function

fn multiply_Number_By_Zero(mut what_Number: i32) {
 what_Number = what_Number*0;
 println!("what_Number value is :{}",what_Number);
}

fn main(){
 let number:i32 = 10;
 multiply_Number_By_Zero(number);
 println!("The value of number after executing a function is:{}",number);
}

Output for above code

what_Number value is : 0
The value of number after executing a function is: 10


RUST Function parameter By Reference

When passing value by reference if any modification happen inside the function, that change will also be carried over to where it was called from.

Example of passing parameter by Reference in function

fn multiply_Number_By_Zero(what_Number:&mut i32) {
 *what_Number = 0;
}

fn main(){
 let number:i32 = 10;
 multiply_Number_By_Zero(&number);
 println!("The value of number after executing a function is:{}",number);
}

Output for above code

The value of number after executing a function is: 10


Conclusion

In this page (written and validated by ) you learned about Rust Function passing parameter . What's Next? If you are interested in completing Rust tutorial, your next topic will be learning about: Rust Recursive Function.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.