doufang8282 2015-03-20 14:28
浏览 2530
已采纳

如何动态清除golang中类型结构实例的值?

Is it possible with golang to make a method that dynamically clears the values of a instance of a struct? btw Im new to golang.

type A struct {
    Name string
    Level int
}

type B struct {
    Skill string
}

func main() {
    a := A{"Momo", 1}
    b := B{"Starfall"}

    // outputs
    // {"Momo", 1}
    // {"Starfall"}

    clear(a)
    clear(b)

    // outputs
    // { , 0}
    // { }
}

func clear(v interface{}) {
    // some code
}
  • 写回答

4条回答 默认 最新

  • dongyun9120 2015-03-20 15:06
    关注

    You can't modify the original values without passing a pointer to them.

    It's much easier and more clear to simply assign a new zero value in your code. If your types are more complex, you can replace the values with a constructor, or provide Reset() methods for your types with a pointer receiver.

    If you really want to see how to do it via reflection your clear function could look like: http://play.golang.org/p/g0zIzQA06b

    func clear(v interface{}) {
        p := reflect.ValueOf(v).Elem()
        p.Set(reflect.Zero(p.Type()))
    }
    

    (This will panic if you pass in a non-pointer value)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大