gpt4 book ai didi

Go Relflect 声明类型结构

转载 作者:IT王子 更新时间:2023-10-29 01:42:09 26 4
gpt4 key购买 nike

我希望我可以恢复我的结构类型并声明该类型的变量。

我试过 Reflect 但我找不到路。

  package main

import (
"fmt"
"reflect"
)

type M struct {
Name string
}

func main() {
type S struct {
*M
}

s := S{}
st := reflect.TypeOf(s)
Field, _ := st.FieldByName("M")
Type := Field.Type
test := Type.Elem()
fmt.Print(test)
}

最佳答案

reflect.New 与您的类型一起使用,这是使用反射在 M 结构的新实例上设置 Name 的示例:

package main

import (
"fmt"
"reflect"
)

type M struct {
Name string
}

func main() {
type S struct {
*M
}

s := S{}
mStruct, _ := reflect.TypeOf(s).FieldByName("M")
mInstance := reflect.New(mStruct.Type.Elem())
nameField := mInstance.Elem().FieldByName("Name")
nameField.SetString("test")
fmt.Print(mInstance)
}

关于Go Relflect 声明类型结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37189768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com