November 2017
Intermediate to advanced
670 pages
17h 35m
English
Here are our base classes:
type Int32 int32type Int64 int64type Float32 float32type IntSlice []int
We can see from our type definitions that we will be able to sum any two of these base types.
Here’s the Int32 implementation of Sum:
func (i Int32) Sum(s Sum) int64 { it := int64(i) switch x := s.(type) { case Int64: return it + int64(x) case Int32: return it + int64(x) case Float32: return it + int64(x) case IntSlice: sum := int64(0) for _, num := range x { sum += int64(num) } return it + sum default: return 0 }}
Notice that we return zero if the value we are trying to add our Int32 to is not in the accepted list of types.