它是int的类型转换器?

时间:2014-07-24 05:43:42

标签: go

我有一本书中的代码示例:

要走的路:对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类型?

2 个答案:

答案 0 :(得分:6)

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.

答案 1 :(得分:1)

这是一种类型断言 - 请参阅the Go Spec