使用接口的字段类型设置结构字段

编程入门 行业动态 更新时间:2024-10-24 10:15:33
本文介绍了使用接口的字段类型设置结构字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以使用反射设置界面字段?当我尝试设置它时,它惊慌地说该值不可寻址.

Is there any way to set an interface field using reflect? When i tried to set it, it paniced saying that the value is non addressable.

type A interface{...} func CreateA(name string) A {...} type B struct { field A should A mirror A } // normal way of initializing var b = B{ field: CreateA("field"), should: CreateA("should"), mirror: CreateA("mirror"), } func MirrorField(b *B) { t := reflect.TypeOf(b) v := reflect.ValueOf(b) for i := 0; i < t.NumField(); i++ { setTo = CreateA(t.Field(1).Name) fieldVal := v.Field(i) fieldVal.Set(reflect.ValueOf(setTo)) } } // what i want is something like var b = &B{} MirrorField(b)

推荐答案

接口没有字段,它们仅定义包含它们的值的方法集.在界面上进行反射时,可以使用 Value.Elem() .

Interfaces don't have fields, they only define a method set of the value they contain. When reflecting on an interface, you can extract the value with Value.Elem().

您也不能设置未导出的字段.您需要将 B 类型的字段名称大写.遍历字段时,请使用 Value.CanSet() 测试它们是否可设置. CanSet()还将返回false,因为该值不可寻址,或者该值仍在接口中.

You also can't Set unexported fields. You need to capitalize the field names in your B type. When iterating over the fields, use Value.CanSet() to test if they are settable. CanSet() will also return false is the value isn't addressable, or the value is still in an interface.

您的代码的有效示例: play.golang/p/Mf1HENRSny

A working example of your code: play.golang/p/Mf1HENRSny

更多推荐

使用接口的字段类型设置结构字段

本文发布于:2023-07-30 00:40:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1245016.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   接口   类型   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!