In this lesson, we explore the concept of passing arguments by value in functions. There are two primary methods for passing arguments: passing by value and passing by reference. In this guide, our focus is on passing by value. Passing by value means that when you pass a variable to a function, its value is copied to a new memory location. Any modifications made to the parameter within the function affect only the copy, leaving the original variable unchanged. Basic data types such as integers, floats, booleans, and strings are all passed by value.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
When a variable is passed by value, its original location in memory remains unchanged even if the function alters the copied parameter.
Memory Layout Example
Consider a scenario where a variablea is declared inside the main function. The variable a is stored in memory at a particular address. When a is passed to the function modify, the value is copied to another memory location. As a result, any modification within modify does not impact the original value of a.
Imagine a memory layout as shown below:
a remains 10.
Go Code Example: Integers
Below is a Go code snippet that demonstrates passing by value with integer data:a remains unchanged after the modify function is called.
Go Code Example: Strings
Now consider an example with a string. In this case, a string variable is created with the value"hello". The string is printed, passed to a function called modify that attempts to change its value to "world", and then printed again. Despite the change within the function, the original string remains "hello" because it was passed by value.
s inside the modify function is simply a copy of the variable a. Thus, when s is updated to "world", the original variable a remains unchanged.
Passing by value means that a copy of the variable is provided to the function. Any changes to the parameter inside the function do not alter the original variable outside the function.