Skip to content

Instantly share code, notes, and snippets.

@whileD
Created July 11, 2017 09:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save whileD/e189d2be8e3c05465490e27293e52cc0 to your computer and use it in GitHub Desktop.
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