An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
Robert Griesemer & Ian Lance Taylor Generics GopherCon 2021
3 generics Robert
- Type Parameter functions types
- type interface
- Type inference generics
Type Parameter
[P, Q constraint#1, R constraint#2]
type parameter function function min
func min(x, y float64) float64 { if x < y { return x } return y}
float64 type generics function
func min[T constraints.Ordered](x, y T) T { if x < y { return x } return y}
constraints.Ordered type constraint meta-type type type package standard constaints constraint type <
m := min[int](2, 3)
type [int]
instantiation
fmin := min[float64]m := fmin(2.71, 3.14)
fmin generic function instantiation
Parameter Type custom type
type Tree[T interface{}] struct { left, right *Tree[T] data T}func (t *Tree[T]) Lookup(x T) *Tree[T]var stringTree Tree[string]
generic type
Type constraint interface
constraint
constraint Go interface define method type
interface { int|string|bool}
constraints
package constraintstype Ordered interface { Integer|Float|~string}
constraint type integer floating-point string method
~string type underlying string
in line
[S interface{ ~[]E }, E interface{}]
[S ~[]E, E interface{}]
empty interface{} alias type
[S ~[]E, E any]
Type inference
func min[T constraints.Ordered](x, y T) Tvar a, b, m float64m = min[float64](a, b)
type argument compiler type T
m = min(a, b)
Robert type inference
Ian use case generics Ian generics Ian
type
generic generic
generics
- function slices, maps channels type generics
- data structure
type Tree[T any] struct { cmp func(T, T) int root *node[T]}type node[T any] struct { left, right *node[T] data}func (bt *Tree[T]) find(val T) **node[T] { pl := &bt.root for *pl != nil { switch cmp := bt.cmp(val, (*pl).data); { case cmp < 0: pl = &(*pl).left case cmp > 0: pl = &(*pl).right default: return pl } } return pl}
find type T compare >
<
generic
operating type parameter function method
- method slice slice type ()
type SliceFn[T any] struct { s []T cmp func(T, T) bool}func (s SliceFn[T]) Len() int { return len(s.s) }func (s SliceFn[T]) Swap(i, j int) { s.s[i], s.s[j] = s.s[j], s.s[i]) }func (s SliceFn[T]) Less(i, j int) bool { return s.cmp(s.s[i], s.s[j]) }func SortFn[T any](s []T, cmp func(T, T) bool) { sort.Sort(SliceFn[T]{s, cmp})}
sort slice slice slice generic
Ian generics
- method type interface
- method type interface
- operation type generics
Ian type parameter
tools tools
Original Link: https://dev.to/pallat/srupcchaak-robert-griesemer-ian-lance-taylor-eruueng-generics-ainngaan-gophercon-2021-13n7
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To