登录
首页 >  Golang >  Go问答

在Go中如何使用名称设置结构体字段的嵌套字段?

来源:stackoverflow

时间:2024-02-22 21:36:20 281浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《在Go中如何使用名称设置结构体字段的嵌套字段?》,聊聊,我们一起来看看吧!

问题内容

我有一个结构,其中一个字段是另一个结构,我想通过名称(作为参数)访问该结构。我遵循使用反射,如何设置结构体字段的值?它适用于基本类型,但不适用于复合类型。

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

解决方案


您想要使用 value

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

Here it is running on the Go playground

今天关于《在Go中如何使用名称设置结构体字段的嵌套字段?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>