0
0
Goprogramming~5 mins

Struct usage patterns in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a struct in Go?
A struct in Go is a collection of fields grouped together to form a single data type. It is used to represent complex data by combining different values under one name.
Click to reveal answer
beginner
How do you define a struct type in Go?
You define a struct type using the type keyword followed by the struct name and the struct keyword with fields inside curly braces. Example:<br>
type Person struct {
  Name string
  Age  int
}
Click to reveal answer
intermediate
What is struct embedding and why is it useful?
Struct embedding is when one struct includes another struct as a field without a name. It allows the embedded struct's fields and methods to be accessed directly, enabling composition and code reuse.
Click to reveal answer
beginner
How do you create a new instance of a struct with field values?
You create a new struct instance by specifying the struct type and initializing fields inside curly braces. Example:<br>
p := Person{Name: "Alice", Age: 30}
Click to reveal answer
intermediate
What is the difference between value and pointer receivers in struct methods?
Value receivers get a copy of the struct, so changes inside the method don't affect the original. Pointer receivers get the address, so changes inside the method modify the original struct. Use pointer receivers to modify data or avoid copying large structs.
Click to reveal answer
How do you access a field named Age from a struct variable p?
Ap["Age"]
Bp.Age
Cp->Age
DAge.p
What happens if you embed a struct Address inside another struct Person?
AEmbedding is not allowed in Go.
BYou must always use Address field name to access fields.
CYou can access Address fields directly from Person.
DPerson becomes a pointer automatically.
Which keyword is used to define a new struct type?
Afunc
Bstruct
Cvar
Dtype
Why use pointer receivers in struct methods?
ATo modify the original struct inside the method.
BTo make a copy of the struct.
CTo prevent method calls.
DPointer receivers are not allowed.
How do you create a struct instance with default zero values?
ABoth A and C
Bvar p Person
Cp := Person{}
Dp := new(Person)
Explain how struct embedding works and give an example of when you might use it.
Think about how one struct can include another to reuse code.
You got /3 concepts.
    Describe the difference between value and pointer receivers in struct methods and why it matters.
    Consider what happens when you want to change the struct inside a method.
    You got /3 concepts.