diff --git a/interfaces/09-stringer/book.go b/interfaces/09-stringer/book.go index d3b26d4..a7977d2 100644 --- a/interfaces/09-stringer/book.go +++ b/interfaces/09-stringer/book.go @@ -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) } diff --git a/interfaces/09-stringer/list.go b/interfaces/09-stringer/list.go index aef1569..7b48878 100644 --- a/interfaces/09-stringer/list.go +++ b/interfaces/09-stringer/list.go @@ -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) } }