登录
首页 >  Golang >  Go问答

为何无法传递具有 *interface{} 参数的结构指针?

来源:stackoverflow

时间:2024-02-19 23:27:25 284浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《为何无法传递具有 *interface{} 参数的结构指针?》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我在 google 上找不到任何有关 *interface{} 的信息。那么...问题是为什么这两种方法的工作方式不同?

package main

type MyStruct struct {}

func valI(x interface{}) {}
func pointI(x *interface{}) {}

func valS(s MyStruct) {}
func pointS(s *MyStruct) {}

func main() {
    s := MyStruct{}
    p := &s

    valI(s)
    valI(p) // Why? Success
    pointI(s) // Why?  Fail: cannot use s (type S) as type *interface {} in argument to point: *interface {} is pointer to interface, not interface
    pointI(p) // Why?  Fail: cannot use p (type *S) as type *interface {} in argument to point: *interface {} is pointer to interface, not interface

    valS(s)
    valS(p) // It's obvious to me why these two fail
    pointS(s) // -//-
    pointS(p)
}

演示:https://play.golang.org/p/pio5vf-fbxh


解决方案


接口包含指向底层数据和类型信息的指针。当您将非接口值分配给接口(或将非接口值作为接口参数传递)时,编译器会生成代码以将类型和指针传递给基础数据。在某种程度上,接口是一个结构:

type interface struct {
   data pointer
   type type
}

指向接口的指针只是指向该结构实例的指针。

所有值都满足 interface{} 接口,因此您可以在需要 interface{} 的地方传递结构体或 *struct。 *interface{}是指向接口的指针,只能传递指向接口的指针:

x:=interface{}(s)
pointI(&x)

今天关于《为何无法传递具有 *interface{} 参数的结构指针?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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