Home »
Golang
Go Pass Struct as Function Arguments
Last Updated : July 22, 2025
In Go, structs can be passed to functions either by value or by reference using pointers. When passed by value, a copy of the struct is made, and changes inside the function do not affect the original. When passed by reference, the original struct can be modified inside the function.
Passing Struct by Value
When a struct is passed by value, the function receives a copy of the original struct, and any modifications inside the function do not affect the original data.
Example
The following example shows how passing a struct by value does not change the original struct:
package main
import "fmt"
type Student struct {
name string
score int
}
func updateScore(s Student) {
s.score = 90
fmt.Println("Inside function:", s)
}
func main() {
s1 := Student{name: "Amit", score: 75}
updateScore(s1)
fmt.Println("In main:", s1)
}
When you run the above code, the output will be:
Inside function: {Amit 90}
In main: {Amit 75}
Explanation
- The
updateScore
function receives a copy of the Student
struct.
- Modifications made inside the function do not affect the original struct in
main
.
Passing Struct by Reference
To allow the function to modify the original struct, you can pass a pointer to the struct.
Example
The following example shows how passing a struct by reference allows the function to update the original data:
package main
import "fmt"
type Student struct {
name string
score int
}
func updateScoreByRef(s *Student) {
s.score = 90
fmt.Println("Inside function:", *s)
}
func main() {
s1 := Student{name: "Priya", score: 75}
updateScoreByRef(&s1)
fmt.Println("In main:", s1)
}
When you run the above code, the output will be:
Inside function: {Priya 90}
In main: {Priya 90}
Explanation
- The
updateScoreByRef
function accepts a pointer to a Student
struct.
- Using the pointer, the function modifies the original struct.
Go Pass Struct as Function Arguments Exercise
Select the correct option to complete each statement about passing structs as function arguments in Go.
- When a struct is passed by value to a function:
- To modify the original struct in a function, you must:
- Which of the following is a correct way to pass a struct by reference?
Advertisement
Advertisement