我在使用Printf 的%T进行输出的时候,发现变量v的类型是string,但是我定义一个string类型的变量A,然后使用 A = v的时候,会报错:cannot convert v (type interface {}) to type string: need type assertion 这个怎么处理。怎么把interface的类型转成 string呢? 谢谢各位大神。
有疑问加站长微信联系(非本文作者)

我在使用Printf 的%T进行输出的时候,发现变量v的类型是string,但是我定义一个string类型的变量A,然后使用 A = v的时候,会报错:cannot convert v (type interface {}) to type string: need type assertion 这个怎么处理。怎么把interface的类型转成 string呢? 谢谢各位大神。
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
`单行代码`
A.(string) 类型断言
只能 是 interface 类型来兼容自定义结构等强类型, 不能反过来,强类型来 兼容interface 类型! GO可是非常强类型的语言。
学习了,正好今天遇到类似的问题。 interface类型 . (需要转换的类型), 注意中间的点号,在进行类型转换前,最好先进行类型的判别: func checkType(v1, v2 interface{}) error { if reflect.TypeOf(v1) != reflect.TypeOf(v2) { return errors.New("Types not ok") }
} 这样会安全一些。