×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Structures

Go Slices

Go Maps

Go Pointers

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

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.

  1. When a struct is passed by value to a function:
  2. To modify the original struct in a function, you must:
  3. Which of the following is a correct way to pass a struct by reference?

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.