Generics·Q112·Medium
Before Go 1.18 you had two choices for reusable code: write it once per type (or with go generate ), or accept interface{} and give up static typing. With any the…
Generics·Q113·Medium
For a single argument they behave almost the same. The differences show up in three places: Same type across parameters and results: func Pick[T fmt.Stringer](a, b T) T…
Generics·Q114·Medium
A constraint is an interface that limits which type arguments are allowed. Since Go 1.18 an interface defines a type set . It can list methods, type terms ( int | string…
Generics·Q115·Medium
~T means "every type whose underlying type is T". Without the tilde, only the exact type T itself matches. Named types such as type Celsius float64 or time.Duration…
Generics·Q116·Hard
Every interface denotes a type set : A method element gives the set of all types that have that method. A union A | B gives the union of the two sets. Elements on…
Generics·Q117·Hard
comparable is a predeclared constraint for types that support == and != . It covers booleans, numbers, strings, pointers, channels, arrays and structs of comparable…
Generics·Q118·Hard
An operation is allowed on a value of type T only if it is valid for every type in T's type set, and the spec explicitly permits it: Operators ( + , < , == ) work if…
Generics·Q119·Hard
Go infers type arguments in two ways: Function argument inference unifies parameter types with argument types. Constraint type inference derives a parameter from another…
Generics·Q120·Medium
No. A generic function is not a value until it is instantiated . There are no "generic function values", so f := Map fails with cannot use generic function Map without…
Generics·Q121·Medium
You cannot write return nil , and you cannot write T{} for an arbitrary T . nil is not valid for int, and composite literals need a core type. Use one of these idioms:…
Generics·Q122·Hard
func IsNil[T any](v T) bool { return any(v) == nil } func main() { var p *int var err error fmt.Println(IsNil(p), IsNil[any](nil), IsNil(err), IsNil[error](nil)) }…
Generics·Q123·Medium
type MyInt int func Describe[T any](v T) string { switch any(v).(type) { case int: return "int" case fmt.Stringer: return "Stringer" default: return "other" } } func…
Generics·Q124·Hard
Methods can use their receiver type's parameters, but a method cannot declare new type parameters of its own. func (l List[T]) Map[U any](f func(T) U) List[U] is…
Generics·Q125·Medium
The receiver must list the type's parameters by name, and you may rename them. You cannot repeat or tighten the constraints in the receiver, and you cannot specialize a…
Generics·Q126·Hard
The main restrictions, several of which exist to keep method sets statically known: No embedding a type parameter: type Wrapper[T any] struct{ T } fails with "embedded…
Generics·Q127·Hard
Problem: you want to create values of type T inside a generic function and call a method that has a pointer receiver , such as UnmarshalText or Set . T itself does not…
Generics·Q128·Hard
An interface can itself have type parameters. That lets a constraint refer to the type being constrained, similar to F-bounded polymorphism or Java's Comparable<T> . It…
Generics·Q129·Hard
The goal is to preserve the caller's named slice type . With []E in and []E out, a named type like type IDs []int comes back as a plain []int , and its methods are lost.…
Generics·Q130·Hard
Go uses a hybrid of the two classic strategies. Full monomorphization (C++, Rust) makes one copy per type. Full boxing (Java) makes one copy for everything. Go instead…
Generics·Q131·Medium
Interviewers want judgment, not enthusiasm. Guidance, broadly following Ian Lance Taylor's "When To Use Generics": When you only call methods: if the function just calls…
Generics·Q132·Medium
type Stack[T any] struct{ items []T } func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) } func (s *Stack[T]) Pop() (T, bool) { var zero T if len(s.items) == 0…
Generics·Q133·Medium
type Tree[K cmp.Ordered, V any] struct { root *node[K, V] size int } type node[K cmp.Ordered, V any] struct { key K val V left, right *node[K, V] } func (t *Tree[K, V])…
Generics·Q134·Medium
type Set[T comparable] map[T]struct{} func SetOf[T comparable](vs ...T) Set[T] { s := make(Set[T], len(vs)) for _, v := range vs { s[v] = struct{}{} } return s } func (s…
Generics·Q135·Hard
type Cache[K comparable, V any] struct { mu sync.Mutex items map[K]*entry[V] } type entry[V any] struct { once sync.Once val V err error } func NewCache[K comparable, V…
Generics·Q136·Medium
func Map[T, U any](xs []T, f func(T) U) []U { out := make([]U, len(xs)) for i, x := range xs { out[i] = f(x) } return out } func Filter[S ~[]E, E any](xs S, keep func(E)…
Generics·Q137·Medium
x/exp/constraints was the experimental home for common constraints: Signed , Unsigned , Integer , Float , Complex and Ordered . Only Ordered moved into the standard…
Generics·Q138·Medium
cmp (Go 1.21) provides Ordered , Compare(a, b) int (returns -1, 0 or +1) and Less(a, b) bool . Go 1.22 added Or(vals ...T) T , which returns the first non-zero argument…
Generics·Q139·Medium
slices : Sort , SortFunc , BinarySearch , Index , Contains , Insert , Delete , DeleteFunc , Compact , Equal , Clone , Grow , Reverse , Max , Min . Iterator helpers (Go…
Generics·Q140·Hard
iter.Seq[V] is a generic function type, func(yield func(V) bool) , and iter.Seq2[K, V] is the two-value form. for v := range seq calls seq with a compiler-generated…
Generics·Q141·Hard
Range-over-func iterators are push iterators: the sequence drives the loop. That makes it impossible to step through two sequences in lockstep with a single for .…
Generics·Q142·Hard
A type definition , type Set[T comparable] map[T]struct{} , creates a new, distinct named type that can have methods. A type alias , type A = B , is just another name…
Generics·Q143·Hard
No. Go generics are invariant . Each instantiation is a distinct named type, and there is no subtyping between instantiations, even when the type arguments are related…
Generics·Q144·Hard
func Nest[T any](n int) { if n > 0 { Nest[[]T](n - 1) } } func main() { Nest[int](3) } Result: compile error instantiation cycle: T instantiated as []T . Go instantiates…
Generics·Q145·Hard
type Pair[K comparable, V any] struct { Key K Val V } type Box[T any] struct{ v T } type MyInt int func main() { fmt.Printf("%T\n", Pair[string, int]{})…
Generics·Q146·Hard
func Merge[T any](ctx context.Context, chans ...<-chan T) <-chan T { out := make(chan T) var wg sync.WaitGroup for _, c := range chans { wg.Go(func() { // Go 1.25;…
Generics·Q147·Medium
Optional fields in API structs (JSON, protobuf, AWS SDK) are often pointers, and &42 or &"x" is not valid Go. Before generics every library shipped aws.String ,…