Implementing interface methods using generic type structures in Go

WBOY
Release: 2024-02-06 08:20:04
forward
473 people have browsed it

在 Go 中使用泛型类型结构实现接口方法

Question content

I want an interface that can pass arguments of any type to its individual methods, and I want an interface with A single implementation structure for generics.

This is a super simplified version of my problem:

package main

type MyInterface interface {
    Set(val any)
}

type MyStruct[T any] struct {
    val T
}

func NewMyStruct[T any]() *MyStruct[T] {
    return &MyStruct[T]{}
}

func (s *MyStruct[T]) Set(val T) {
    s.val = val
}

func main() {
    var obj MyInterface
    obj = NewMyStruct[any]() // accepted
    obj = NewMyStruct[int]() // not accepted
    obj = NewMyStruct[string]() // not accepted
}
Copy after login

Is there a way to satisfy the compiler's requirements without losing the type information of the Set method when directly processing the structure?


Correct answer


Code

I think your code can be modified like this

package main

import "fmt"

type MyInterface[T any] interface {
    Set(value T)
}

type MyStruct[T any] struct {
    val T
}

func NewMyStruct[T any]() *MyStruct[T] {
    return &MyStruct[T]{}
}

func (s *MyStruct[T]) Set(val T) {
    s.val = val
}

func main() {
    var obj1 MyInterface[int]
    obj1 = NewMyStruct[int]()

    var obj2 MyInterface[string]
    obj2 = NewMyStruct[string]()

    var obj3 MyInterface[any]
    obj3 = NewMyStruct[any]()
}
Copy after login

illustrate

Whenever a parameterized type is used, the type parameters in its definition must be replaced with the actual type. This means that the generic type in the interface must be instantiated. For this, your interface should be declared like this.

// As-is
type MyInterface interface {
    Set(val any)
}
// To-be
type MyInterface[T any] interface {
    Set(val T)
}
Copy after login

And when using it, you should be clear about what type the any is using.

func main() {
    var obj1 MyInterface[int]
    obj1 = NewMyStruct[int]()
}
Copy after login

I quoted two pages

[1] Go error: Cannot use a generic non-instantiated type

[2] How to implement a universal interface?

The above is the detailed content of Implementing interface methods using generic type structures in Go. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template