Interfaces in Go
Go: Interfaces
Interfaces are named collections of method signatures.
It defines a set of behaviors that a type must implement in order to be considered an instance of that interface.
How to define an interface in Go:
Here's an example of how to define an interface in Go:
type Shape interface {
Area() float64
Perimeter() float64
}
In this example, we define an interface called Shape
that has two method signatures: Area()
and Perimeter()
. Any type that implements these two methods will be considered an instance of the Shape
interface.
How to implements an interface in Go
To implement an interface, we have to define a struct and provide implementations for the methods in the interface:
type Rectangle struct {
Width float64
Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
In this example, we define a struct called Rectangle
with two fields: Width
and Height
. We then provide implementations for the Area()
and Perimeter()
methods in the Shape
interface. Since the Rectangle
struct has these two methods, it is considered an instance of the Shape
interface.
How to create a function using interface
You can use an interface to create a function that accepts any type that implements the interface:
func PrintShapeInfo(s Shape) {
fmt.Println("Area:", s.Area())
fmt.Println("Perimeter:", s.Perimeter())
}
r := Rectangle{Width: 10, Height: 5}
PrintShapeInfo(r)
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go