Created
July 11, 2017 09:53
-
-
Save whileD/e189d2be8e3c05465490e27293e52cc0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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