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 stringfield to the anonymousreaksi(reaction) struct and print its value; - replace
%+vwith%vand compare the output.