Skip to content

Instantly share code, notes, and snippets.

func TestSet(t *testing.T) {
set := NewSet()
set.Add("the")
set.Add("quick")
set.Add("brown")
set.Add("fox")
set.Add("the")
if !set.Has("quick") {
type StringSet struct {
items map[string]int
}
func NewSet() StringSet {
return StringSet{items: make(map[string]int)}
}
func (s *StringSet) Add(item string) {
s.items[item] = 1
func TestTStackInt(t *testing.T) {
stack := &TStack[int]{}
stack.Push(100)
stack.Push(200)
stack.Push(300)
stack.Push(400)
if stack.Peek() != 400 {
t.Error(stack.Peek())
}
func TestTStack(t *testing.T) {
stack := &TStack[string]{}
stack.Push("the")
stack.Push("quick")
stack.Push("brown")
stack.Push("fox")
if stack.Peek() != "fox" {
t.Error(stack.Peek())
}
type TStack[T constraints.Ordered] struct {
items []T
}
func (s *TStack[T]) Push(item T) {
s.items = append(s.items, item)
}
func (s *TStack[T]) Pop() (item T) {
if !s.IsEmpty() {
func TestStringStack(t *testing.T) {
stack := &StringStack{}
stack.Push("the")
stack.Push("quick")
stack.Push("brown")
stack.Push("fox")
if stack.Peek() != "fox" {
t.Error(stack.Peek())
}
type StringStack struct {
items []string
}
func (s *StringStack) Push(item string) {
s.items = append(s.items, item)
}
func (s *StringStack) Pop() (item string) {
if !s.IsEmpty() {
import "golang.org/x/exp/constraints"
type Number interface {
constraints.Integer | constraints.Float
}
func AddNumbers[T Number](a, b T) T {
return a + b
}
@sausheong
sausheong / add.go
Created May 16, 2022 05:23
generics
func Add[T int | float64](a, b T) T {
return a + b
}
type Integer struct {
...
}
func (i Integer) Plus(a Number) Number {
...
}