为什么我不能传递带有 *接口{} 参数的结构指针?



我在谷歌上找不到关于*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)

最新更新