Creating a struct
- Go course
- Beginner
- Lesson 70/90
- 4 min
Learn to create struct values and assign fields.
Creating structs
A struct value is created in three ways:
k1 := Kitap{Title: "Dune", Sayfa: 412} // named fields (recommended)
k2 := Kitap{"Dune", "Herbert", 412} // positional, all fields
k3 := &Kitap{Title: "Dune"} // a pointerWith named fields, omitted fields get their zero value (k1.Yazar == ""). The positional form must give every field and breaks when a field is added to the struct.
Anonymous and nested structs
An unnamed struct can be used for one-off data; it is common in tests and JSON responses:
nokta := struct{ X, Y int }{3, 4}
fmt.Println(nokta.X) // 3A struct field can be another struct:
type Adres struct{ Sehir string }
type Kisi struct {
Ad string
Adres Adres
}
k := Kisi{Ad: "Ada", Adres: Adres{Sehir: "İzmir"}}
fmt.Println(k.Adres.Sehir)Practice Nested struct
Define the structs Adres (Sehir string) and Kisi (Ad string, Adres Adres). Create Kisi{Ad: "Ada", Adres: Adres{Sehir: "İzmir"}} with named fields and print k.Ad + " - " + k.Adres.Sehir.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Adres struct{ Sehir string }
type Kisi struct {
Ad string
Adres Adres
}
func main() {
k := Kisi{Ad: "Ada", Adres: Adres{Sehir: "İzmir"}}
fmt.Println(k.Ad + " - " + k.Adres.Sehir)
}Expected output
Ada - İzmir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why doesn't <code>Kitap{"Dune", 412}</code> (Yazar omitted) compile?
- 412 isn't a string and goes to Yazar
- Both are true Correct answer
- It compiles
- The positional form must give every field
Explanation: The positional form must match the field count; also 412 would be assigned to the second field, Yazar (a string). The named-field form avoids this mistake.
2 Named field
k := Kitap{____: "Dune", Sayfa: 412}
k := Kitap{Title: "Dune", Sayfa: 412}
Explanation: In the named-field form, the field name is written before the colon.
3 Form and result
| Term | Meaning |
|---|---|
Kitap{Title: "X"} |
Others zero |
Kitap{"X", "Y", 1} |
Positional, all fields |
&Kitap{} |
*Kitap |
struct{ X int }{1} |
Anonymous struct |