Types, Methods, and Interfaces Flashcards
What are concrete types in Go?
Types that use primitive or compound types, specifying how data is stored and providing method implementations.
What is the scope of types declared within a block in Go?
Types declared within a block are scoped to that block.
What is the difference between concrete and abstract types in Go?
Concrete types specify how data is stored, while abstract types specify what a type should do.
How do you define a method for a user-defined type in Go?
Define it at the package level with a receiver specification, e.g., func (p Person) String() string
.
How do you invoke a method on a user-defined type in Go?
Example: p := Person{"Fred", "Fredson", 52}
output := p.String()
What is the difference between pointer and value receivers in Go?
Pointer receivers modify the receiver, while value receivers do not.
What is the best practice for method receivers in Go?
Use pointer receivers consistently for all methods.
What does Go automatically do for pointer and value receivers?
Go automatically takes the address for pointer receivers and dereferences pointers for value receivers.
What happens when you call a method with a value receiver on a nil instance in Go?
It panics.
Can methods be assigned to variables in Go?
Yes, methods can be assigned to variables, like closures, to access the type’s instance fields.
When should you use methods instead of functions in Go?
Use methods when the logic depends on values initialized at startup (e.g., structs).
How does Go avoid inheritance?
Types based on another type have the same underlying type but no hierarchy; type conversion is required.
What is the purpose of the iota
keyword in Go?
It is used for defining enumerations with a limited set of values.
What is composition via embedding in Go?
Go allows embedding types in structs to reuse methods and fields, but it is not inheritance.
How does Go’s interface system work?
Interfaces define a method set that concrete types must implement; they are type-safe and follow duck typing.