这是一个将类型转换为整数的类型转换器吗?

huangapple go评论82阅读模式
英文:

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 (
	&quot;fmt&quot;
)

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 &lt; 10; i++ {
		fmt.Printf(&quot;%vth even: %v\n&quot;, 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 &lt;- retVal
		}
	}
	retFunc := func() Any {
		return &lt;-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&#39;s int value, otherwise the runtime will panic.

答案2

得分: 1

这是一种类型断言-请参阅Go规范

英文:

It's a type assertion - see the Go Spec.

huangapple
  • 本文由 发表于 2014年7月24日 13:43:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/24925949.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定