如何将通用接口作为GO中的函数/方法参数传递?

发布于 2025-02-05 12:55:38 字数 1268 浏览 2 评论 0原文

我是新手,想知道如何在没有定义为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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文