![]() |
VOOZH | about |
In Go, an interface is a type that lists methods without providing their code. You can’t create an instance of an interface directly, but you can make a variable of the interface type to store any value that has the needed methods.
type Shape interface {
Area() float64
Perimeter() float64
}
In this example, Shape is an interface that requires any type implementing it to have Area and Perimeter methods.
type InterfaceName interface {
Method1() returnType
Method2() returnType
}
In Go, to implement an interface, a type must define all methods declared by the interface. Implementation is implicit, meaning no keyword (such as implements) is needed.
C Area: 78.53981633974483 C Perimeter: 31.41592653589793 R Area: 12 R Perimeter: 14
An interface can hold any value, but the actual value and its type are stored dynamically.
Value of s: <nil> Type of s: <nil>
Here, since s is unassigned, it shows <nil> for both value and type.
Type assertion allows extracting the underlying type of an interface.
Syntax
value := interfaceVariable.(ConcreteType)Example
Area: 16
A type switch can be used to compare the dynamic type of an interface against multiple types.
Syntax
switch variable.(type) {
case type1:
// Code for type1
case type2:
// Code for type2
default:
// Code if no types match
}
Example:
Circle area: 78.54 Rectangle area: 12.00