Reputation: 34081
I have a code sample from a book:
The Way To Go: A Thorough Introduction To The Go Programming Language
from which I could not figure out how something works. Look at the code:
package main
import (
"fmt"
)
type Any interface{}
type EvalFunc func(Any) (Any, Any)
func main() {
evenFunc := func(state Any) (Any, Any) {
os := state.(int)
ns := os + 2
return os, ns
}
even := BuildLazyIntEvaluator(evenFunc, 0)
for i := 0; i < 10; i++ {
fmt.Printf("%vth even: %v\n", i, even())
}
}
func BuildLazyEvaluator(evalFunc EvalFunc, initState Any) func() Any {
retValChan := make(chan Any)
loopFunc := func() {
var actState Any = initState
var retVal Any
for {
retVal, actState = evalFunc(actState)
retValChan <- retVal
}
}
retFunc := func() Any {
return <-retValChan
}
go loopFunc()
return retFunc
}
func BuildLazyIntEvaluator(evalFunc EvalFunc, initState Any) func() int {
ef := BuildLazyEvaluator(evalFunc, initState)
return func() int {
return ef().(int)
}
}
Look at the code line:
return ef().(int)
What's happening here? Does the compiler convert the result into an int type?
Upvotes: 0
Views: 373
Reputation: 5755
x := ef() // x is of type Any, which is actually an interface{}
y := x.(int) // this is a type assertion, if the contents of x are an interface, y will be assigned x's int value, otherwise the runtime will panic.
Upvotes: 6