gpt4 book ai didi

go - 使用go的struct指针作为接口(interface)

转载 作者:IT王子 更新时间:2023-10-29 01:54:33 26 4
gpt4 key购买 nike

我想将结构方法作为函数值传递。如果函数需要返回 interface{} 而它返回 *struct,为什么编译会失败?如果我尝试从声明为返回接口(interface){}(包装函数)的函数中返回 *struct,它会完美地工作。

package main

func main() {
println("hello")
testInterface(wrapper) // works
instance := MyStruct{}
testInterface(instance.works) // works
testInterface(instance.fails) // fails: ./main.go:8: cannot use instance.fails (type func(int) *MyStruct) as type func(int) interface {} in argument to testInterface
}

func testInterface(f func() interface{}) {
f()
return
}

type MyStruct struct {
}

func (s *MyStruct) works() interface{} {
return s
}

func (s *MyStruct) fails() *MyStruct {
return s
}

func wrapper() interface{} {
s := MyStruct{}
return s.fails()

最佳答案

那是因为它不适合 assignability标准

A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:

  • x's type is identical to T.
  • x's type V and T have identical underlying types and at least one of V or T is not a named type.
  • T is an interface type and x implements T.
  • x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type.
  • x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
  • x is an untyped constant representable by a value of type T.

因此,这解释了为什么 testInterface(instance.fails) 失败:因为 instance.fails 不可分配给 f func() 接口(interface){}

现在第二个问题:

It perfectly works if I try to return *struct from function that is declared to return interface{} (wrapper func).

它工作正常,因为 *struct 类型的值可分配给 interface{} 类型,因为:

  1. 这条可分配性规则:“T 是一个接口(interface)类型,x 实现了 T。”
  2. “一个类型实现任何接口(interface),包括其方法的任何子集,因此可以实现几个不同的接口(interface)。例如,所有类型都实现空接口(interface):”(粗体是我的)

引用资料:

关于go - 使用go的struct指针作为接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43466757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com