update: interfaces lecture

This commit is contained in:
Inanc Gumus
2019-08-23 11:03:51 +03:00
parent 435c08e800
commit e0b2786fd9
3 changed files with 88 additions and 9 deletions

View File

@ -22,6 +22,8 @@ func (l list) print() {
} }
for _, it := range l { for _, it := range l {
// fmt.Printf("(%-10T) --> ", it)
it.print() it.print()
// you cannot access to the discount method of the game type. // you cannot access to the discount method of the game type.
@ -29,3 +31,18 @@ func (l list) print() {
// it.discount(.5) // it.discount(.5)
} }
} }
// PREVIOUS CODE:
// type list []*game
// func (l list) print() {
// if len(l) == 0 {
// fmt.Println("Sorry. Our store is closed. We're waiting for the delivery 🚚.")
// return
// }
// for _, it := range l {
// it.print()
// }
// }

View File

@ -15,15 +15,13 @@ func main() {
rubik = puzzle{title: "rubik's cube", price: 5} rubik = puzzle{title: "rubik's cube", price: 5}
) )
// thanks to the printer interface we can add different types of values
// to the list.
//
// only rule: they need to implement the `printer` interface.
// to do that: each type needs to have a print method.
var store list var store list
store = append(store, &minecraft, &tetris, mobydick, rubik) store = append(store, &minecraft, &tetris, mobydick, rubik)
tetris.discount(.8)
// printer(tetris).discount(.8)
store.print() store.print()
}
// p can store a value of any type that has a `print()` method
var p printer
p = puzzle{title: "sidewinder", price: 10}
p.print()
}

View File

@ -0,0 +1,64 @@
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"math/rand"
"time"
)
// Socket has the power!
type Socket struct {
power int
}
// Plug a device to draw power from the `Socket`
func (s *Socket) Plug(device PowerDrawer) {
n := rand.Intn(50)
s.power -= n
device.Draw(n)
}
// PowerDrawer can be any type that can be powered
type PowerDrawer interface {
Draw(power int)
}
// -----
// Kettle can be powered
type Kettle struct{}
// Draw power to a Kettle
func (Kettle) Draw(power int) {
fmt.Printf("Kettle is drawing %dkW of electrical power.\n", power)
}
// Mixer can be powered
type Mixer struct{}
// Draw power to a Mixer
func (Mixer) Draw(power int) {
fmt.Printf("Mixer is drawing %dkW of electrical power.\n", power)
}
// -----
func main() {
rand.Seed(time.Now().UnixNano())
kettle := Kettle{}
mixer := Mixer{}
socket := &Socket{100}
socket.Plug(kettle)
socket.Plug(mixer)
fmt.Printf("Socket's available power is %d kW.\n", socket.power)
}