首页 > 解决方案 > 如何在 Go 中按名称设置结构字段的复合字段?

问题描述

我有一个结构,其中一个字段是另一个结构,我想按名称(作为参数)访问这个结构。我跟着Using reflect,你如何设置结构字段的值?它适用于基本类型,但不适用于复合类型。

package main

import (
    "fmt"
    "reflect"
)


type PntInt struct {
    p *int64
}

type Foo struct {
    X  int64
    Px PntInt
}

func main() {
    foo := Foo{}
    fmt.Println(foo)
    i := int64(8)
    Pi := PntInt{&i}
    reflect.ValueOf(&foo).Elem().FieldByName("X").SetInt(i)
    reflect.ValueOf(&foo).Elem().FieldByName("Px").Set(Pi)
    fmt.Println(foo)
}

设置整数有效,但尝试设置“Px”失败并出现错误

./prog.go:25:52: cannot use Pi (type PntInt) as type reflect.Value in argument to reflect.ValueOf(&foo).Elem().FieldByName("Px").Set

标签: gostructreflect

解决方案


你想使用一个Value

reflect.ValueOf(&foo).Elem().FieldByName("Px").Set(reflect.ValueOf(Pi))

它在 Go 操场上运行


推荐阅读