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.