refactor: stringer

This commit is contained in:
Inanc Gumus
2019-09-27 19:09:07 +03:00
parent 0127b45c1e
commit e6eba7314f
16 changed files with 130 additions and 65 deletions

View File

@@ -10,10 +10,15 @@ package main
import "fmt"
func main() {
// The money type is a stringer.
// You don't need to call the String method when printing a value of it.
// var pocket money = 10
// fmt.Println(pocket)
store := list{
&book{product{"moby dick", 10}, toTimestamp(118281600)},
&book{product{"odyssey", 15}, toTimestamp("733622400")},
&book{product{"hobbit", 25}, unknown},
&book{product{"hobbit", 25}, toTimestamp(nil)},
&puzzle{product{"rubik's cube", 5}},
&game{product{"minecraft", 20}},
&game{product{"tetris", 5}},
@@ -22,12 +27,12 @@ func main() {
store.discount(.5)
// the store doesn't have a print method anymore.
// but the Print function can print it.
// it's because, the list satisfies the stringer.
// The list is a stringer.
// The `fmt.Print` function can print the `store`
// by calling `store`'s `String()` method.
//
// Underneath, `fmt.Print` uses a type switch to
// detect whether a type is a Stringer:
// https://golang.org/src/fmt/print.go#L627
fmt.Print(store)
// timestamp is useful even if it's zero.
var ts timestamp
fmt.Println(ts)
}