Interface declaration
- Go course
- Beginner
- Lesson 81/90
- 4 min
Learn to declare an interface with type ... interface.
Defining interfaces
An interface is a list of methods describing what a type can do. What matters is not which type it is but which behavior it offers:
type Sekil interface {
Alan() float64
}
func toplamAlan(sekiller []Sekil) float64 {
t := 0.0
for _, s := range sekiller {
t += s.Alan()
}
return t
}toplamAlan works with circles, squares or any shape added later, as long as it has an Alan() float64 method.
Small interfaces
In Go interfaces are usually very small; most have a single method: io.Reader (Read), io.Writer (Write), fmt.Stringer (String), error (Error). Small interfaces are easy to satisfy and can be combined: type ReadWriter interface { Reader; Writer }. The proverb: "The bigger the interface, the weaker the abstraction."
Practice Shapes
Write the Sekil interface (Alan() float64) and the types Kare (Kenar float64) and Dikdortgen (En, Boy float64). Print the total area for []Sekil{Kare{2}, Dikdortgen{3, 4}}.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Sekil interface {
Alan() float64
}
type Kare struct{ Kenar float64 }
type Dikdortgen struct{ En, Boy float64 }
func (k Kare) Alan() float64 { return k.Kenar * k.Kenar }
func (d Dikdortgen) Alan() float64 { return d.En * d.Boy }
func main() {
t := 0.0
for _, s := range []Sekil{Kare{2}, Dikdortgen{3, 4}} {
t += s.Alan()
}
fmt.Println(t)
}Expected output
16
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the zero value of an interface variable?
- nil Correct answer
- An empty struct
- 0
- Undefined
Explanation: An interface with no value assigned is nil; calling a method on a nil interface panics.
2 Interface type
type Sesli ____ {
Ses() string
}
type Sesli interface {
Ses() string
}
Explanation: type Name interface { ... } defines a list of methods.
3 Interface and its method
| Term | Meaning |
|---|---|
io.Reader |
Read |
io.Writer |
Write |
fmt.Stringer |
String |
error |
Error |