Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
package main
type IntegerPair struct {
First int
Second int
}
func NewIntegerPair(f, s int) *IntegerPair {
return &IntegerPair{First: f, Second: s}
}
func (p *IntegerPair) Sum() int {
return p.First + p.Second
}
func (p *IntegerPair) Diff() int {
return abs(p.First - p.Second)
}
func abs(i int) int {
if i < 0 {
i *= -1
}
return i
}
package main
import "testing"
func TestIntegerPairSum(t *testing.T) {
pair := NewIntegerPair(1, 2)
sum := pair.Sum()
if sum != 3 {
t.Errorf("Arithmetic error: %d + %d = %d\n",
pair.First, pair.Second, sum)
}
pair = NewIntegerPair(-1, -4)
sum = pair.Sum()
if sum != -5 {
t.Errorf("Arithmetic error: %d + %d = %d\n",
pair.First, pair.Second, sum)
}
}
func TestIntegerPairDiff(t *testing.T) {
pair := NewIntegerPair(1, 2)
diff := pair.Diff()
if diff != 1 {
t.Errorf("Arithmetic error: abs(%d - %d) = %d\n",
pair.First, pair.Second, diff)
}
pair = NewIntegerPair(-1, -4)
diff = pair.Diff()
if diff != 3 {
t.Errorf("Arithmetic error: abs(%d - %d) = %d\n",
pair.First, pair.Second, diff)
}
}
package main
import "fmt"
import "reflect"
func ShowPair(p ...Pair) {
for _, v := range p {
fmt.Printf("type:%s, sum:%d, diff:%d",
reflect.TypeOf(v), v.Sum(), v.Diff())
}
}
func main() {
p := NewIntegerPair(1, 2)
ShowPair(p)
}
package main
type Pair interface {
Sum() int
Diff() int
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment