Skip to content

Instantly share code, notes, and snippets.

@mitsuse
Created July 4, 2014 15:06
Show Gist options
  • Save mitsuse/f8bd687b9399db98079f to your computer and use it in GitHub Desktop.
Save mitsuse/f8bd687b9399db98079f to your computer and use it in GitHub Desktop.
An interface named "Number" accepts numeric types such as "Int", "Float" and so on.
package main
import "fmt"
type Number interface {
Add(x Number) Number
Sub(x Number) Number
}
type Int int
func (this Int) Add(x Number) Number {
switch number := x.(type) {
case Int:
return this + number
case Float:
return Float(this) + number
default:
// undefined
}
return nil
}
func (this Int) Sub(x Number) Number {
switch number := x.(type) {
case Int:
return this - number
case Float:
return Float(this) - number
default:
// undefined
}
return nil
}
type Float float64
func (this Float) Add(x Number) Number {
switch number := x.(type) {
case Int:
return this + Float(number)
case Float:
return this + number
default:
// undefined
}
return nil
}
func (this Float) Sub(x Number) Number {
switch number := x.(type) {
case Int:
return this - Float(number)
case Float:
return this - number
default:
// undefined
}
return nil
}
func main() {
x := Int(10)
y := Float(3.4)
fmt.Printf("x = %v\n", x)
fmt.Printf("y = %v\n\n", y)
fmt.Printf("x + y = %v\n", x.Add(y))
fmt.Printf("y + x = %v\n\n", y.Add(x))
fmt.Printf("x - y = %v\n", x.Sub(y))
fmt.Printf("y - x = %v\n\n", y.Sub(x))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment