Files
learngo/interfaces/composition/list.go

49 lines
802 B
Go
Raw Normal View History

// 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
2019-08-27 15:21:17 +03:00
import (
"fmt"
"strings"
)
type item interface {
2019-08-30 00:49:27 +03:00
sum() money
discount(float64)
2019-08-27 15:21:17 +03:00
fmt.Stringer // same as: `String() string`
}
type list []item
2019-08-27 15:21:17 +03:00
func (l list) String() string {
if len(l) == 0 {
2019-08-27 15:21:17 +03:00
return "Sorry. We're waiting for delivery 🚚."
}
2019-08-27 15:21:17 +03:00
var str strings.Builder
for _, it := range l {
2019-08-27 15:21:17 +03:00
fmt.Fprintf(&str, "%s\n", it)
}
2019-08-27 15:21:17 +03:00
fmt.Fprintf(&str, "\tTOTAL : $%.2f", l.sum())
return str.String()
}
2019-08-27 15:21:17 +03:00
func (l list) sum() (total money) {
for _, it := range l {
total += it.sum()
}
return
}
2019-08-27 15:21:17 +03:00
func (l list) discount(ratio float64) {
for _, it := range l {
2019-08-30 00:49:27 +03:00
it.discount(ratio)
}
}