update: interfaces
This commit is contained in:
@@ -15,6 +15,5 @@ type book struct {
|
||||
}
|
||||
|
||||
func (b book) print() {
|
||||
// b is a copy of the original `book` value here.
|
||||
fmt.Printf("%-15s: $%.2f \n", b.title, b.price)
|
||||
}
|
||||
|
||||
@@ -18,17 +18,6 @@ func (g *game) print() {
|
||||
fmt.Printf("%-15s: $%.2f\n", g.title, g.price)
|
||||
}
|
||||
|
||||
// + discount gets a copy of `*game`.
|
||||
// + discount can update the original `game` through the game pointer.
|
||||
// + it's better to use the same receiver type: `*game` for all methods.
|
||||
func (g *game) discount(ratio float64) {
|
||||
g.price *= (1 - ratio)
|
||||
}
|
||||
|
||||
// PREVIOUS CODE:
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// + `g` is a copy: `discount` cannot change the original `g`.
|
||||
// func (g game) discount(ratio float64) {
|
||||
// g.price *= (1 - ratio)
|
||||
// }
|
||||
}
|
||||
@@ -21,8 +21,6 @@ func (l list) print() {
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("My Store:\n")
|
||||
fmt.Printf("---------\n")
|
||||
for _, it := range l {
|
||||
it.print()
|
||||
|
||||
|
||||
@@ -16,37 +16,18 @@ func main() {
|
||||
)
|
||||
|
||||
var store list
|
||||
|
||||
store = append(store, &minecraft, &tetris, mobydick, rubik)
|
||||
|
||||
tetris.discount(.8)
|
||||
// printer(tetris).discount(.8)
|
||||
|
||||
store.print()
|
||||
}
|
||||
|
||||
/*
|
||||
var my list
|
||||
// type printer interface {
|
||||
// print()
|
||||
// }
|
||||
|
||||
// + only the `*game` have methods.
|
||||
// + `game` doesn't have any methods.
|
||||
// + `item` interface couldn't be satisfied with a `game` value.
|
||||
// + it can only be satisfied with a `*game` value.
|
||||
// my = my.add(minecraft)
|
||||
my = append(my, &minecraft)
|
||||
my = append(my, &tetris)
|
||||
my = append(my, &mobydick)
|
||||
|
||||
// interface value stores a pointer to minecraft
|
||||
minecraft.discount(.5)
|
||||
my.list()
|
||||
|
||||
my.discount(.5)
|
||||
my.list()
|
||||
*/
|
||||
|
||||
// ! cannot add mobydick to the store: it's a book type, not a game type.
|
||||
// interfaces to the rescue!
|
||||
// mobydick := book{title: "moby dick", price: 10}
|
||||
// my.add(&mobydick)
|
||||
// ----------------------------------------------------------------
|
||||
// p can store a value of any type that has a `print()` method
|
||||
var p printer
|
||||
p = puzzle{title: "sidewinder", price: 10}
|
||||
p.print()
|
||||
}
|
||||
Reference in New Issue
Block a user