doubo1871 2016-05-16 15:25
浏览 56
已采纳

如何通过反射初始化空指针

This is a very straight forward question.

How do you implement Initialize() below with reflect? Or is this possible?

func Initialize(v interface{}) {
    // ... some reflection code
}

type MyType struct {
    Name string
}

func main() {
    var val *MyType

    // val is nil before initialize
    Initialize(val)
    // val is now &MyType{Name: ""}

    // ...
}

```

  • 写回答

1条回答 默认 最新

  • doujian3132 2016-05-16 15:40
    关注

    Here's how to do it:

    func Initialize(v interface{}) {
      rv := reflect.ValueOf(v).Elem()
      rv.Set(reflect.New(rv.Type().Elem()))
    }
    

    This function must be called with a pointer to the value to set:

    Initialize(&val)
    

    playground example

    The code in this answer panics if the argument type is not a pointer to a pointer. Depending on your use, you might want to check the reflect value kind before calling Elem().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示