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

如何动态清除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条)

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动