

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Structs in Go
incomplete
2: Nested Structs in Go
incomplete
3: Anonymous Structs in Go
incomplete
4: Embedded Structs
incomplete
5: Struct Methods in Go
incomplete
6: Memory Layout
incomplete
7: Empty Struct
incomplete
8: Empty Struct
incomplete
9: Update Users
incomplete
10: Send Message
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
An anonymous struct is just like a normal struct, but it is defined without a name and therefore cannot be referenced elsewhere in the code.
To create an anonymous struct, just instantiate the instance immediately using a second pair of brackets after declaring the type:
myCar := struct {
brand string
model string
} {
brand: "Toyota",
model: "Camry",
}
You can even nest anonymous structs as fields within other structs:
type car struct {
brand string
model string
doors int
mileage int
// wheel is a field containing an anonymous struct
wheel struct {
radius int
material string
}
}
var myCar = car{
brand: "Rezvani",
model: "Vengeance",
doors: 4,
mileage: 35000,
wheel: struct {
radius int
material string
}{
radius: 35,
material: "alloy",
},
}
In general, prefer named structs. Named structs make it easier to read and understand your code, and they have the nice side-effect of being reusable. I sometimes use anonymous structs when I know I won't ever need to use a struct again. For example, sometimes I'll use one to create the shape of some JSON data in HTTP handlers.
If a struct is only meant to be used once, then it makes sense to declare it in such a way that developers down the road won't be tempted to accidentally use it again.