You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 10:48:04