Skip to content

Instantly share code, notes, and snippets.

@hantuo
Last active September 7, 2018 16:55
Show Gist options
  • Save hantuo/574aeda064c18eb69aa6806fbb259510 to your computer and use it in GitHub Desktop.
Save hantuo/574aeda064c18eb69aa6806fbb259510 to your computer and use it in GitHub Desktop.
Generic as a kind of types -- type T generic {int, float64}

Generic function implementation:

/*

* "generic" is a KIND of types, just like "struct", "map", "interface", etc...
* "T" is a generic type (a type of kind generic).
* var t = T{int} is a value of type T, values of generic types looks like a "normal" type

*/

type T generic {
	int
	float64
	string
}

func Sum(a, b T{}) T{} {
	return a + b
}

Function caller:

Sum(1, 1) // 2
// same as:
Sum(T{int}(1), T{int}(1)) // 2

Generic struct implementation:

type ItemT generic {
	interface{}
}

type List struct {
	l []ItemT{}
}

func NewList(t ItemT) *List {
	l := make([]t)
	return &List{l}
}

func (p *List) Push(item ItemT{}) {
	p.l = append(p.l, item)
}

Caller:

list := NewList(ItemT{int})
list.Push(42)
@hantuo
Copy link
Author

hantuo commented Sep 7, 2018

Polymorphism in Go must fit smoothly into the surrounding language, without awkward special cases and without exposing implementation details. For example, it would not be acceptable to limit type parameters to those whose machine representation is a single pointer or single word. As another example, once the general Keys(map[K]V) []K function contemplated above has been instantiated with K = int and V = string, it must be treated semantically as equivalent to a hand-written non-generic function. In particular it must be assignable to a variable of type func(map[int]string) []int.

var f func(a, b int) int = func(a, b int) int { return Sum(a, b) }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment