CodeBlanks Logo Icon CodeBlanks

Struct declaration

Learn to define a struct with type.

Defining structs

A struct is a type that groups related data into named fields:

type Kitap struct {
    Title string
    Yazar  string
    Sayfa  int
}

Fields starting with an upper-case letter are visible outside the package (and to libraries such as JSON); lower-case ones only inside it. Go has no classes; data is expressed with structs and behavior with methods.

Comparing structs

Structs whose fields are all comparable can be compared with == and can be map keys. When a struct is assigned, all of its fields are copied:

a := Kitap{"Dune", "Herbert", 412}
b := a
b.Sayfa = 500
fmt.Println(a.Sayfa, a == b)  // 412 false

Structs with slice or map fields can't be compared with ==.

Practice Book struct

Define the Kitap struct (Title, Yazar, Sayfa). Create a := Kitap{"Dune", "Herbert", 412}, copy it with b := a, set b.Sayfa = 500 and print a.Sayfa and b.Sayfa.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

type Kitap struct {
    Title string
    Yazar  string
    Sayfa  int
}

func main() {
    a := Kitap{"Dune", "Herbert", 412}
    b := a
    b.Sayfa = 500
    fmt.Println(a.Sayfa, b.Sayfa)
}

Expected output

412 500

Questions and answers

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

1 After <code>var k Kitap</code>, what is <code>k.Sayfa</code>?

  • 0 Correct answer
  • nil
  • Undefined
  • A compile error

Explanation: Every field of a struct starts with its own zero value: string "", int 0.

2 Struct type

Question
type Nokta ____ {
    X, Y int
}
Answer
type Nokta struct {
    X, Y int
}

Explanation: type Name struct { ... } defines a new struct type.

3 Field and visibility

Term Meaning
Title Exported
sayfa Package-private
var k Kitap Zero-valued fields
b := a All fields are copied

All lessons in Beginner