add: fmt.stringer to item interface

This commit is contained in:
Inanc Gumus
2019-09-02 17:03:19 +03:00
parent 83b32e4170
commit 86a59253d1
2 changed files with 18 additions and 12 deletions

View File

@ -22,11 +22,12 @@ type book struct {
func (b *book) String() string {
p := format(b.published)
// product.String has a pointer receiver.
// that's why we need to take its address here.
// product.String() has a pointer receiver.
// That's why you need to manually take the product's address here.
//
// when you put a value in an interface, the interface
// cannot run that value's type's value-receiver methods.
// If you pass: "b.product", Go would pass it as a copy to Sprintf.
// In that case, Go can't deference b.product automatically.
// It's because: b.product would be different value—a copy.
return fmt.Sprintf("%s - (%v)", &b.product, p)
}

View File

@ -12,7 +12,18 @@ import (
"strings"
)
type list []fmt.Stringer
type item interface {
discount(float64)
// item interface embeds the fmt.Stringer interface.
//
// Go adds all the methods of the fmt.Stringer
// to the item interface.
fmt.Stringer // same (see below): String() string
// String() string
}
type list []item
// list satisfies the fmt.Stringer
func (l list) String() string {
@ -35,13 +46,7 @@ func (l list) String() string {
}
func (l list) discount(ratio float64) {
type discounter interface {
discount(float64)
}
for _, it := range l {
if it, ok := it.(discounter); ok {
it.discount(ratio)
}
it.discount(ratio)
}
}