使用反射,如何初始化结构指针字段的值? [英] Using reflect, how do you initialize value of a struct pointer field?

查看:38
本文介绍了使用反射,如何初始化结构指针字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

package main

import (
    "fmt"
    "reflect"
)

type A struct {
    D *int
}

func main() {
    a := &A{}
    v := reflect.ValueOf(a)
    e := v.Elem()
    f := e.Field(0)
    z := reflect.Zero(f.Type().Elem())
    f.Set(z)
    fmt.Println(z)
}

panic:reflect.Set:int类型的值不能分配给* int

panic: reflect.Set: value of type int is not assignable to type *int

如何使用反射将* D设置为默认值

how to set the *D to default value use reflect

推荐答案

您需要具有一个指针值(* int),但是 func零(典型类型)的 reflect 文档状态)值:

You need to have a pointer value (*int), but the reflect documentation states for func Zero(typ Type) Value that:

返回的值既不可寻址也不可设置.

The returned value is neither addressable nor settable.

您可以使用 New :

z := reflect.New(f.Type().Elem())

这篇关于使用反射,如何初始化结构指针字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆