简体   繁体   中英

How to create a generic struct?

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 eg

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

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 — ie 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

Gotip Playground: https://gotipplay.golang.org/p/Qyd6zTLdkRn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM