我有一本书中的代码示例:
前进之路: Go编程语言的全面介绍
我不知道什么东西是怎么工作的。看看代码:
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)
}
}
请看代码行:
return ef().(int)
这里发生了什么事?编译器是否将结果转换为int类型?
发布于 2014-07-24 05:52:58
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.
发布于 2014-07-24 14:18:23
这是一个类型断言--参见围棋特快。
https://stackoverflow.com/questions/24925949
复制相似问题