Go course

StructsAnonymous Structs

Go

Display

Theme

Structs · Code example

Anonymous Structs

Sometimes you need a struct just once, in one place, and there's no point naming the type. For that, Go gives you anonymous structs: you write the type definition and the value together.

server := struct {
	Host string
	Port int
}{
	Host: "localhost",
	Port: 8080,
}

fmt.Println(server.Host, server.Port)

The first part (struct { ... }) is the type; the second part ({ ... }) is the value.

Fields with an anonymous struct type

An anonymous struct can also be the type of a field. That's a good fit for data that only makes sense as part of its parent struct:

type Pesan struct {
	Pengirim string
	Isi      string
	Lampiran struct {
		NamaFile string
		UkuranKB int
	}
}

var p Pesan
p.Lampiran.NamaFile = "foto.jpg"

Here a Pesan (message) has a sender, content, and an attachment (Lampiran) with a file name and size.

When should you use one?

  • Temporary data, like a small config inside a single function.
  • Test data (test cases) — you've already seen this in the tests for this course: cases := []struct{ ... }{ ... }.

If you need the same type in more than one place, it's better to give it a name with type.

Try it yourself

Run the example in the editor with Run. Then try this:

  • add an Emoji string field to the anonymous reaksi (reaction) struct and print its value;
  • replace %+v with %v and compare the output.
main.go
package main

import "fmt"

type Pesan struct {
	Pengirim string
	Isi      string
	Lampiran struct {
		NamaFile string
		UkuranKB int
	}
}

func main() {
	// Struct anonim: konfigurasi grup chat yang hanya dipakai di sini.
	grup := struct {
		Nama        string
		MaksAnggota int
		Publik      bool
	}{
		Nama:        "Alumni SMA 3",
		MaksAnggota: 256,
		Publik:      false,
	}
	fmt.Printf("%+v\n", grup)

	// Field bertipe struct anonim.
	var p Pesan
	p.Pengirim = "Lina"
	p.Isi = "Ini foto reuni kemarin"
	p.Lampiran.NamaFile = "reuni.jpg"
	p.Lampiran.UkuranKB = 820
	fmt.Printf("%+v\n", p)

	reaksi := struct {
		Dari  string
		Jenis string
	}{"Tono", "suka"}
	fmt.Println(reaksi.Dari, "memberi reaksi", reaksi.Jenis, "pada pesan", p.Pengirim)
}

Output

Go runtime not loaded yet

Press Run to see what the program prints.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + S: tidy the code (gofmt)