Home > front end >  How to create a generic struct?
How to create a generic struct?

Time:09-17

How can I construct a generic struct?

I tried:

type SafeSet[type T] struct {
    Values map[T]bool
}

I want to be able to do e.g.

SafeSet{ Values: make(map[net.Conn]bool) }
SafeSet{ Values: make(map[string]  bool) }
SafeSet{ Values: make(map[int]     bool) }

CodePudding user response:

You can't do that with the current Go version, 1.17. Unfortunately there's nothing else to say.


After generics will be added to the language, probably in Go 1.18 (early 2022), the syntax for such a parametrized types, according to the current accepted proposal, will be:

type SafeSet[T comparable] struct {
    Values map[T]bool
}

In particular:

  • The type constraint comes after the type name T
  • If you want to use T as a map key, you must use the built-in constraint comparable, because map keys must be comparable — i.e. support == operator.

Then you have to instantiate the parametrized type with an actual type argument:

Example:

To use a generic type, you must supply type arguments. This is called instantiation. The type arguments appear in square brackets, as usual. When we instantiate a type by supplying type arguments for the type parameters, we produce a type in which each use of a type parameter in the type definition is replaced by the corresponding type argument.

    s0 := SafeSet[net.Conn]{Values: make(map[net.Conn]bool)}
    s1 := SafeSet[string]{Values: make(map[string]bool)}
    s2 := SafeSet[int]{Values: make(map[int]bool)}

Since instantiating SafeSet literals looks kinda verbose, you can use a generic constructor func:

func NewSafeSet[T comparable]() SafeSet[T] {
    return SafeSet[T]{Values: make(map[T]bool)}
}

The syntax is, obviously, the same, except that in this case you are explicitly instantiating the function with the type arg:

    s3 := NewSafeSet[uint64]()
    s3.Values[200] = true

Go2 Playground: https://go2goplay.golang.org/p/Qyd6zTLdkRn

  • Related