gointermediate
Go Interfaces
Interfaces, type assertions and type switches
7 questions
By EZ4Code Team
1. How are Go interfaces implemented?
Implicitly: a type implements an interface as long as it implements all the interface's methods
Explicitly declare implements
Through inheritance
Through annotations
Explanation: Go interfaces are implemented implicitly; as long as a type implements all the methods defined by the interface, it automatically satisfies the interface without explicit declaration.
2. What does the empty interface interface{} mean?
Can hold values of any type
Cannot hold any value
Can only hold nil
Is an error type
Explanation: The empty interface interface{} (Go 1.18+ can be written as any) has no methods; any type satisfies it and can hold any value, similar to Object in other languages.
3. What is the syntax for a type assertion?
var i interface{} = "hello"
s, ok := i.(string)v, ok := i.(T)
v := i as T
v := (T)i
v := i<T>
Explanation: i.(T) is a type assertion; the two-value form v, ok := i.(T) returns ok as false on failure instead of panicking; the single-value form panics on failure.
4. What is a type switch used for?
Branching based on the concrete type of an interface value
Iterating over a slice
Declaring a new type
Selecting a channel
Explanation: switch v := i.(type) branches based on the concrete type of the interface value; in each case, v is narrowed to the corresponding type.
5. What does the internal structure of an interface value contain?
Type information (type) and a value pointer (value)
Only the value
Only the type
A method list
Explanation: A Go interface value internally consists of a dynamic type (eface/iface's _type) and a dynamic value (data pointer).
6. What is the difference between a nil interface and an interface holding a nil value?
A nil interface is itself nil; an interface holding a nil value has type information and is not nil
They are completely identical
An interface holding a nil value is nil
A nil interface has type information
Explanation: A nil interface has both type and value as nil; assigning a value of a concrete type that is nil to an interface gives the interface type information, so it != nil, which is a common pitfall.
7. Method set rules: what is the relationship between the method sets of type T and *T?
The method set of *T includes the method set of T, but not vice versa
The method set of T includes the method set of *T
Their method sets are completely identical
Neither has a method set
Explanation: The method set of *T includes all methods with receivers T and *T; the method set of T only includes methods with receiver T. Therefore *T may implement more interfaces.