making interfaces koans better

This commit is contained in:
Steven Degutis
2012-03-26 18:00:36 -05:00
parent dedbcb2fcc
commit 52956ab14e
3 changed files with 39 additions and 16 deletions

View File

@@ -5,7 +5,7 @@ func aboutChannels() {
assert(len(ch) == __int__) // channels are like buffers
ch<- "foo" // i mean, "metaphors are like similes"
ch <- "foo" // i mean, "metaphors are like similes"
assert(len(ch) == __int__) // they can be queried for queued items
@@ -21,7 +21,7 @@ func aboutChannels() {
assert(__delete_me__) // we'll need to make room for the queue, or suffer deadlocks
ch<- "bar" // this send will succeed
ch<- "quux" // there's enough room for this send too
ch<- "extra" // but the buffer only has two slots
ch <- "bar" // this send will succeed
ch <- "quux" // there's enough room for this send too
ch <- "extra" // but the buffer only has two slots
}

View File

@@ -1,10 +1,19 @@
package go_koans
func aboutInterfaces() {
mspaint := &program{3} // mspaint is a kind of *program, which is a valid 'runner'
runOnce(mspaint) // runOnce takes an abstract 'runner' type
bob := new(human) // bob is a kind of *human
rspec := new(program) // rspec is a kind of *program
assert(mspaint.runTimes == __int__) // conformed interfaces need not be declared, they are inferred
assert(runner(bob) == __runner__) // conformed interfaces need not be declared, they are inferred
assert(bob.milesCompleted == 0)
assert(rspec.executionCount == 0)
runTwice(bob) // bob fits the profile for a 'runner'
runTwice(rspec) // rspec also fits the profile for a 'runner'
assert(bob.milesCompleted == __int__) // bob is affected by running in his own unique way (probably fatigue)
assert(rspec.executionCount == __int__) // rspec can run completely differently than bob, thanks to interfaces
}
// abstract interface and function that requires it
@@ -13,16 +22,27 @@ type runner interface {
run()
}
func runOnce(r runner) {
func runTwice(r runner) {
r.run()
r.run()
}
// concrete type implementing the interface
type human struct {
milesCompleted int
}
func (self *human) run() {
self.milesCompleted++
}
// another concrete type implementing the interface
type program struct {
runTimes int
executionCount int
}
func (self *program) run() {
self.runTimes++
self.executionCount++
}

View File

@@ -10,12 +10,15 @@ import (
"testing"
)
var __string__ string = "impossibly lame value"
var __int__ int = -1
var __byte__ byte = 255
var __bool__ bool = false // ugh
var __float32__ float32 = -1.0
var __delete_me__ bool = false
const (
__string__ string = "impossibly lame value"
__int__ int = -1
__byte__ byte = 255
__bool__ bool = false // ugh
__float32__ float32 = -1.0
__delete_me__ bool = false
)
var __runner__ runner = nil
func TestKoans(t *testing.T) {
aboutNumbers()