英文:
It is a type converter to int?
问题
我有一段来自一本书的代码示例:
《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类型?
英文:
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?
答案1
得分: 6
x := ef() // x 是类型为 Any 的变量,实际上是一个 interface{}
y := x.(int) // 这是一个类型断言,如果 x 的内容是一个 interface,那么 y 将被赋值为 x 的 int 值,否则运行时会引发 panic。
英文:
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.
答案2
得分: 1
这是一种类型断言-请参阅Go规范。
英文:
It's a type assertion - see the Go Spec.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论