栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

指向保存类型的接口的指针

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

指向保存类型的接口的指针

切勿使用指向接口的指针。如果您需要一个指针来使用指针接收器调用方法,则必须将指针放入

interface{}

如果在

interface{}
要使用指针接收器调用方法的位置已经具有值,则需要制作该值的可寻址副本。

您想要完成

i = &i
的工作可能是:

item := i.(Item)i = &item

这将创建原始副本的可寻址副本

Item
,然后将指向该副本的指针放入
i
。请注意,这永远不会更改原始值
Item

如果您不知道中的类型,则可以

interface{}
使用“ reflect”复制值:

func nextVal(i interface{}) {    // get the value in i    v := reflect.ValueOf(i)    // create a pointer to a new value of the same type as i    n := reflect.New(v.Type())    // set the new value with the value of i    n.Elem().Set(v)    // Get the new pointer as an interface, and call NextVal    fmt.Println("NextVal:", n.Interface().(NextValuer).NextVal())    // this could also be assigned another interface{}    i = n.Interface()    nv, ok := i.(NextValuer)    fmt.Printf("i is a NextValuer: %tnNextVal: %dn", ok, nv.NextVal())}

http://play.golang.org/p/gbO9QGz2Tq



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/372735.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号