CodeBlanks Logo Icon CodeBlanks

Struct and pointer

Learn struct pointers and dot access.

Structs and pointers

When accessing fields through a struct pointer you don't need to write (*p).Ad; Go does it automatically: p.Ad.

k := &Kitap{Title: "Dune", Sayfa: 412}
k.Sayfa = 500           // same as (*k).Sayfa = 500
fmt.Println(k.Sayfa)    // 500

Pointers are used to change a struct in a function or to pass a large struct without copying it.

Changing it in a function

If a struct is passed by value the function works on a copy; to keep the change, pass a pointer:

func zamYap(c *Calisan, oran float64) {
    c.Maas *= 1 + oran
}

c := Calisan{Ad: "Ada", Maas: 1000}
zamYap(&c, 0.1)
fmt.Println(c.Maas)  // 1100

Practice Give a raise

Write the Calisan struct (Ad string, Maas float64) and the zamYap(c *Calisan, oran float64) function. Give a 0.1 raise to an employee with Maas: 1000 and print the salary.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

type Calisan struct {
    Ad   string
    Maas float64
}

func zamYap(c *Calisan, oran float64) {
    c.Maas *= 1 + oran
}

func main() {
    c := Calisan{Ad: "Ada", Maas: 1000}
    zamYap(&c, 0.1)
    fmt.Println(c.Maas)
}

Expected output

1100

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the correct way to access a field through a struct pointer?

  • p.Ad Correct answer
  • p->Ad
  • *p.Ad
  • p::Ad

Explanation: Go dereferences the pointer automatically with the dot operator; -> and :: don't exist in Go, and *p.Ad is read as *(p.Ad).

2 Struct pointer

Question
func zamYap(c ____Calisan, oran float64) {
    c.Maas *= 1 + oran
}
Answer
func zamYap(c *Calisan, oran float64) {
    c.Maas *= 1 + oran
}

Explanation: Making the parameter *Calisan lets the function change the real struct.

3 Code and effect

Term Meaning
p.Ad (p *Kitap) Automatic dereference
f(k) (value) The copy changes
f(&k) (pointer) The original changes
&Kitap{...} Creates a pointer

All lessons in Beginner