Go Pass By Value Example

1. Introduction

In Go, when you pass a parameter to a function, you are passing by value. That means the function receives a copy of the variable, and any modifications to the parameter within the function do not affect the original variable. This concept is crucial for understanding how data is manipulated within functions in Go. Let's delve into this by looking at a simple example.

Definition

Passing parameters by value means that a copy of the data is made and used by the called function. In Go, all basic data types like integers, floats, booleans, and even arrays and structs are passed by value.

2. Program Steps

1. Define a function that attempts to modify the value of a parameter.

2. In the main function, declare a variable and pass it to the defined function.

3. Print the value of the variable before and after the function call to observe if any changes occur.

3. Code Program

package main

import "fmt"

// attemptModifyValue takes an integer and tries to modify it.
func attemptModifyValue(x int) {
	x = x * 2 // This modification will not affect the original variable
}

func main() {
	value := 10
	fmt.Println("Before:", value) // Print value before the function call

	attemptModifyValue(value) // Passing value by value
	fmt.Println("After:", value) // Print value after the function call to show it's unchanged
}

Output:

Before: 10
After: 10

Explanation:

1. package main - Defines the main package, a convention for the executable program in Go.

2. import "fmt" - Imports the Format package, used here for input and output operations.

3. The function attemptModifyValue is defined with one parameter x of type int. Inside the function, x is modified, but since it's a copy of the original variable, the original value remains unchanged.

4. Inside the main function, a variable value is declared and initialized to 10.

5. The variable value is then passed to attemptModifyValue. The function receives a copy of value, not the original variable.

6. Before and after calling attemptModifyValue, the fmt.Println function is used to print the value of value.

7. The output demonstrates that despite the function's attempt to modify x, the original value remains unchanged at 10 after the function call, proving that the parameter was passed by value.


Comments