add: type assertion

This commit is contained in:
Inanc Gumus
2019-08-23 17:07:45 +03:00
parent e0b2786fd9
commit 39aed37a88
23 changed files with 291 additions and 48 deletions

View File

@@ -11,6 +11,9 @@ import "fmt"
type printer interface {
print()
// use type assertion when you cannot change the interface.
// discount(ratio float64)
}
type list []printer
@@ -26,59 +29,50 @@ func (l list) print() {
}
}
// type assertion can extract the wrapped value.
// or: it can put the value into another interface.
func (l list) discount(ratio float64) {
// you can declare an interface in a function/method as well.
// interface is just a type.
type discounter interface {
discount(float64)
}
for _, it := range l {
// you can assert to an interface.
// and extract another interface.
if it, ok := it.(discounter); ok {
it.discount(ratio)
}
}
}
//
// type assertion can pull out the real value behind an interface value.
//
// it can also check whether the value convertable to a given type.
//
// ----
// func (l list) discount(ratio float64) {
// for _, it := range l {
// // remember: interface is a type
// if it, ok := it.(interface{ discount(float64) }); ok {
// it.discount(ratio)
// // you can inline-assert interfaces
// // interface is just a type.
// g, ok := it.(interface{ discount(float64) })
// if !ok {
// continue
// }
// g.discount(ratio)
// }
// }
//
// type switch can pull out the real value behind an interface value.
//
// func (l list) discount(ratio float64) {
// for _, it := range l {
// switch it := it.(type) {
// case *game:
// it.discount(ratio)
// case *puzzle:
// it.discount(ratio)
// }
// }
// }
// ----
//
// type switch can find the type behind an interface value.
//
// // type assertion can pull out the real value behind an interface value.
// // it can also check whether the value convertable to a given type.
// func (l list) discount(ratio float64) {
// for _, it := range l {
// switch it.(type) {
// case *game:
// fmt.Print("it's a *game! --> ")
// case *puzzle:
// fmt.Print("it's a *puzzle! --> ")
// default:
// fmt.Print("neither --> ")
// g, ok := it.(*game)
// if !ok {
// continue
// }
// it.print()
// g.discount(ratio)
// }
// }