golang type conversion after type assertion

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

golang type conversion after type assertion

问题

这是两段代码:

  1. http://play.golang.org/p/Oh6xNm2dRK
func main() {
    var media interface{}
    media = "boo"
    media = media.(string)
    fmt.Println([]byte(media))
}
  1. http://play.golang.org/p/Vd-6AGCBKQ
func main() {
    media := "boo"
    fmt.Println([]byte(media))
}

在第一段代码中,media首先被创建为空接口,然后通过类型断言转换为字符串。
在第二段代码中,media直接被声明为字符串。

两者都试图将media转换为字节数组,为什么会有差异呢?它们不都是字符串吗?

英文:

Take these two bits of code:

  1. http://play.golang.org/p/Oh6xNm2dRK
func main() {
	var media interface{}
	media = "boo"
	media = media.(string)
	fmt.Println([]byte(media))
}
  1. http://play.golang.org/p/Vd-6AGCBKQ
func main() {
	media := "boo"
	fmt.Println([]byte(media))
}

In 1. the media is first created as the empty interface and then type asserted to a string.
In 2. the media is a string.

Both try to convert the media to a byte array, why the difference? Aren't they both strings by that time?

答案1

得分: 3

第一个示例不会改变media的类型,它已经被定义为interface{}。你需要将它设置为一个新的字符串变量:

func main() {
	var media interface{}
	media = "boo"
	x := media.(string)
	fmt.Println([]byte(x))
}

或者可以内联实现:

func main() {
	var media interface{}
	media = "boo"
	fmt.Println([]byte(media.(string)))
}
英文:

The first one doesn't change the type of media, which is already defined as interface{}. You need to set it to a new string variable:

func main() {
	var media interface{}
	media = "boo"
	x := media.(string)
	fmt.Println([]byte(x))
}

http://play.golang.org/p/QB3ey_e3io

or do it inline:

func main() {
	var media interface{}
	media = "boo"
	fmt.Println([]byte(media.(string)))
}

http://play.golang.org/p/RJqBJ4telB

huangapple
  • 本文由 发表于 2013年12月20日 10:54:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/20695541.html
匿名

发表评论

匿名网友

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

确定