如何将通用接口作为GO中的函数/方法参数传递?
我是新手,想知道如何在没有定义为GO中函数参数的具体类型的情况下传递通用接口。
示例代码
type GenericInterface [T any] interface {
Print() T
}
type MyStruct struct {
Val string
}
func (m MyStruct) Get() string {
return m.Val
}
func CallGenericInterface(g GenericInterface) {
g.Print()
}
func main() {
myStruct := MyStruct {
Val : "Hello",
}
CallGenericInterface(myStruct)
}
以下是删除代码时的
cannot use generic type GenericInterface[T any] without instantiation
,我会收到错误,说明我能够通过更改我的CallGenericInterface
type GenericInterface [T any] interface {
Print() T
}
type MyStruct struct {
Val string
}
func (m MyStruct) Get() string {
return m.Val
}
func CallGenericInterface(g GenericInterface[any]) {
g.Print()
}
func main() {
myStruct := MyStruct {
Val : "Hello",
}
CallGenericInterface(myStruct)
}
问题是,我无法将My -struct传递给函数调用,并且正在遇到以下错误,
./main.go:100:23: cannot use myStruct (variable of type MyStruct) as type GenericInterface[*any] in argument to CallGenericInterface:
MyStruct does not implement GenericInterface[*any] (missing Print method)
是否有关于Golang中的仿制药或一般概念所缺少的?谢谢
I am new to Go and want to know how I can pass a generic interface without a concrete type defined as a function parameter in Go.
Below is the sample code
type GenericInterface [T any] interface {
Print() T
}
type MyStruct struct {
Val string
}
func (m MyStruct) Get() string {
return m.Val
}
func CallGenericInterface(g GenericInterface) {
g.Print()
}
func main() {
myStruct := MyStruct {
Val : "Hello",
}
CallGenericInterface(myStruct)
}
When I compile the code, I get the error saying that
cannot use generic type GenericInterface[T any] without instantiation
However, I am able to make the error go away by changing the function signature for my CallGenericInterface
function as below
type GenericInterface [T any] interface {
Print() T
}
type MyStruct struct {
Val string
}
func (m MyStruct) Get() string {
return m.Val
}
func CallGenericInterface(g GenericInterface[any]) {
g.Print()
}
func main() {
myStruct := MyStruct {
Val : "Hello",
}
CallGenericInterface(myStruct)
}
However, now the issue is that I am not able to pass myStruct to the function call and am getting the below error
./main.go:100:23: cannot use myStruct (variable of type MyStruct) as type GenericInterface[*any] in argument to CallGenericInterface:
MyStruct does not implement GenericInterface[*any] (missing Print method)
Is there anything I am missing regarding generics in golang or concept in general ? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论