英文:
golang type conversion after type assertion
问题
这是两段代码:
func main() {
var media interface{}
media = "boo"
media = media.(string)
fmt.Println([]byte(media))
}
func main() {
media := "boo"
fmt.Println([]byte(media))
}
在第一段代码中,media首先被创建为空接口,然后通过类型断言转换为字符串。
在第二段代码中,media直接被声明为字符串。
两者都试图将media转换为字节数组,为什么会有差异呢?它们不都是字符串吗?
英文:
Take these two bits of code:
func main() {
var media interface{}
media = "boo"
media = media.(string)
fmt.Println([]byte(media))
}
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)))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论