Go语言使用interface实现类型转换与赋值的疑难问题咨询
错误原因分析
- Go参数是值传递,修改局部形参不影响外部变量
你传入&(a.s)时,是把这个指向a.s的指针值拷贝了一份给到cast函数的形参a。形参a是cast函数内的局部变量,你直接执行a = b.(string),只是把这个局部变量的值改成了字符串BBB,完全没有操作到原指针指向的a.s的内存空间,因此外部的a.s不会有任何变化。 - interface类型的操作逻辑错误
形参a是interface{}类型,它内部存储了两个信息:传入值的类型(此处为*string)、传入值的实际内容(此处为a.s的内存地址)。你要修改原变量的值,必须先把interface{}里存储的*string指针断言出来,再通过解引用操作修改指针指向的内存,而不是直接给interface{}变量本身赋值。
修复后的可运行代码
func main() { a := &A{} cast(&(a.s), "BBB") fmt.Println(a.s) } type A struct { s string } func cast(a interface{}, b interface{}) { // 先断言出interface中存储的*string指针 strPtr, ok := a.(*string) if !ok { // 类型不匹配可自行加错误处理 return } // 解引用指针,直接修改指向的内存值 *strPtr = b.(string) }
通用多类型支持写法
如果要支持多种类型赋值,可以用type switch做类型判断:
import "fmt" func cast(a interface{}, b interface{}) error { switch target := a.(type) { case *string: val, ok := b.(string) if !ok { return fmt.Errorf("value type mismatch: expected string, got %T", b) } *target = val case *int: val, ok := b.(int) if !ok { return fmt.Errorf("value type mismatch: expected int, got %T", b) } *target = val // 按需添加其他类型的分支逻辑 default: return fmt.Errorf("unsupported target type: %T", a) } return nil }
内容的提问来源于stack exchange,提问作者nick_green
相关产品推荐
相关产品推荐

