Member-only story

Passing Structs by Value vs. by Reference in Go

Siva
3 min readJan 27, 2025

Exploring Efficiency and Performance

Balancing Efficiency: Passing Structs by Reference in Go

In Go, understanding the differences between passing structs by value and by reference is crucial for writing efficient and performant code. This blog post will delve into the intricacies of these two methods, highlighting their impact on memory management, garbage collection, and overall performance.

Passing Structs by Value

When you pass a struct by value, a copy of the struct is made. This can be inefficient, especially for large structs, due to the overhead of copying data. Here’s an example:

package main

import "fmt"

type MyLargeStruct struct {
data [1000]int // A large array to simulate a large struct
}

// Less efficient: Struct passed by value
func processByValue(val MyLargeStruct) {
// Process the struct
fmt.Println(val.data[0]) // line number 12:25 val.data[0] escapes to heap
}

func main() {
var largeStruct MyLargeStruct
largeStruct.data[0] = 42

// Pass by value
processByValue(largeStruct)
}

Output

go build -gcflags="-m"  pass_by_value.go 
# command-line-arguments
./pass_by_value.go:15:6: can inline main
./pass_by_value.go:12:16: inlining call to fmt.Println
./pass_by_value.go:12:16: ... argument does not escape…

--

--

Responses (2)