您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

切勿使用指向接口的指针。如果您需要一个指针来使用指针接收器调用方法,则必须将指针放入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 @R_403_1750@ also be assigned another interface{}
    i = n.Interface()
    nv, ok := i.(NextValuer)
    fmt.Printf("i is a NextValuer: %t\nNextVal: %d\n", ok, nv.NextVal())
}

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

其他 2022/1/1 18:17:48 有389人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶