OSGo.008: Go Structs and Methods — Value Copies, Pointers and Receiver Semantics

Conceptual illustration of two rack-monitoring modules and a programming workstation.

Open-Source Go Programming • Intermediate • Estimated study time: 45 minutes.

A struct groups related fields into a single composite value. Methods associate behavior with a named type, allowing programmers to represent a device record together with operations that inspect or modify it. The preceding Go maps lesson introduced keyed lookup; the current laboratory combines keyed records with explicit value and pointer semantics.

Prerequisites and learning objectives

Review Go variables and zero values, functions and parameters and arrays and slices. Install Go and use a local terminal. Learners will declare and initialize structs, explain assignment copies, distinguish value and pointer receivers, use pointer aliases, and update struct values stored in maps. All temperatures are synthetic; do not use the program for equipment control.

Structs and named fields

The official Tour of Go introduces structs as collections of fields. A struct type defines each field’s name and type. A keyed composite literal initializes selected fields explicitly; omitted fields receive their zero values. The dot operator selects a field. Assigning a struct copies its fields, so changing an integer field in a copy does not change the original. A copy of a pointer, map or slice field may still reference shared data. Do not equate a struct assignment with recursive deep copying.

Net Ninja explains custom Go types and struct declarations in lesson 15 of the Go tutorial series. Watch at source.

Methods and receivers

A method has a receiver parameter in addition to its ordinary parameters. A value receiver receives a copy of the original struct; assigning its scalar fields modifies the local copy. A pointer receiver receives a copy of the address, allowing changes to the referenced struct. The Tour of Go methods section and Effective Go explain receiver behavior. A pointer’s zero value is nil; dereferencing nil or accessing fields through nil can panic. Unlike C, Go does not support pointer arithmetic in ordinary safe Go.

The Go pointer-receiver tutorial explains how methods can update fields in the original struct. Watch at source.

For an addressable value r, calling a pointer-receiver method r.Update(30) is shorthand for calling (&r).Update(30). Map elements are not addressable in the same way. To update a struct stored by value in a map, retrieve a copy, update it, and assign the new value back to the key. A map of pointers is another design, but introduces shared mutation and nil-pointer considerations.

Laboratory: rack records and temperature updates

The example declares a rack record with an identifier and temperature in degrees Celsius. It implements a value-receiver preview and a pointer-receiver update. Save the complete example as main.go:

package main
 
import "fmt"
 
type Rack struct {
    ID string
    TempC int
}
 
func (r Rack) Preview(temp int) Rack {
    r.TempC = temp
    return r
}
 
func (r *Rack) Update(temp int) {
    r.TempC = temp
}
 
func check(ok bool, name string) {
    if !ok {
        panic(name)
    }
    fmt.Println("PASS", name)
}
 
func main() {
    r := Rack{ID: "R1", TempC: 24}
    check(r.ID == "R1" && r.TempC == 24, "named fields")
    copy := r
    copy.TempC = 30
    check(r.TempC == 24 && copy.TempC == 30, "independent value copy")
    preview := r.Preview(99)
    check(preview.TempC == 99 && r.TempC == 24, "value receiver")
    r.Update(30)
    check(r.TempC == 30, "pointer receiver")
    p := &r
    p.Update(0)
    check(r.TempC == 0, "pointer alias and zero")
    byID := map[string]Rack{r.ID: r}
    x := byID["R1"]
    x.Update(42)
    check(byID["R1"].TempC == 0, "map value copy")
    byID["R1"] = x
    check(byID["R1"].TempC == 42 && r.TempC == 0, "map writeback")
}

Run the formatter, execute the program and perform static analysis using the following commands:

gofmt -w main.go
go run main.go
go vet main.go

The laboratory was executed using Go 1.23.2 on linux/amd64. The program returned the following seven successful checks, and go vet exited successfully without diagnostics:

PASS named fields
PASS independent value copy
PASS value receiver
PASS pointer receiver
PASS pointer alias and zero
PASS map value copy
PASS map writeback

Engineering interpretation and limitations

The preview returns a proposed record without changing the source. Update modifies the original via its receiver. The pointer p refers to the same rack, so setting the temperature to zero through p changes r. The map stores a separate value copy of r. Updating x changes the local copy until assignment writes x back to the map. The original r remains independent. For concurrent applications, shared mutation needs synchronization or another ownership policy; pointers alone do not make operations thread-safe. Large structs may be costly to copy, but receiver choice should reflect mutation semantics, method sets and consistency rather than presumed performance. Benchmark real workloads before optimizing. The example uses a local variable named copy; in production, avoid shadowing the built-in copy function unless intentional.

Exercises and answer key

Exercise 1: Declare Rack{} and predict its fields. Exercise 2: Explain why preview.TempC is 99 while r.TempC remains 24 immediately after Preview. Exercise 3: Predict r.TempC after p.Update(0). Exercise 4: Explain why the map still contains zero after x.Update(42) but before writeback. Exercise 5: Explain why calling a pointer-receiver method directly on byID[“R1”] does not compile.

Answers: 1. ID is the empty string and TempC is zero. 2. The value receiver holds a copy. 3. Zero because p refers to r. 4. x is a copy of the stored record. 5. A map index expression is not addressable; retrieve into a local variable and write back, or intentionally store pointers.

Conclusion

Structs model related data, and methods organize its behavior. Value receivers preserve independent scalar copies, while pointer receivers permit deliberate updates. Choose copy or alias semantics consciously, and verify map writeback, zero values and shared state before integrating the pattern into production software.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

BitcoinVersus.Tech donation QR code for 5,000 satoshis

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.

BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

One response to “OSGo.008: Go Structs and Methods — Value Copies, Pointers and Receiver Semantics”

  1. […] serialization, signing compatibility and dependencies before migrating production tooling. Our Go programming lesson introduces a general principle relevant to software interfaces: changes in representation and […]

    Like

Leave a Reply