简体   繁体   English

类型断言后的golang类型转换

[英]golang type conversion after type assertion

Take these two bits of code: 1. http://play.golang.org/p/Oh6xNm2dRK 2. http://play.golang.org/p/Vd-6AGCBKQ 取这两段代码: 1。http : //play.golang.org/p/Oh6xNm2dRK 2. http://play.golang.org/p/Vd-6AGCBKQ

In 1. the media is first created as the empty interface and then type asserted to a string. 在1.中,首先将媒体创建为空接口,然后将其声明为字符串。 In 2. the media is a string. 在2.媒体是一个字符串。

Both try to convert the media to a byte array, why the difference? 两者都试图将媒体转换为字节数组,为什么区别? Aren't they both strings by that time? 那个时候它们不是两个字符串吗?

The first one doesn't change the type of media , which is already defined as interface{} . 第一个不会更改已定义为interface{}media类型。 You need to set it to a new string variable, or do it inline: 您需要将其设置为新的字符串变量,或者将其设置为内联:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM