生成模板代码实现Golang泛型
interface{}

1. 实现通用Set数据结构

如何实现一个数据结构(算法也一样)支持常用类型,生成特定类型实现,可以轻松重用。

使用genny,非常简单几个步骤:

genny/genericgeneric.TypeItemTypegenny

下面实现比较简单的Set数据结构,定义ItemSet泛型Set,同时定义了Add和Clean方法:

//go:generate genny -in=$GOFILE -out=gen-$GOFILE gen "Item=string,int"

package set

import "github.com/cheekybits/genny/generic"

// Item the type of the Set
type Item generic.Type

// ItemSet the set of Items
type ItemSet struct {
	items map[Item]bool
}

func (s *ItemSet)Add(t Item) ItemSet  {
	if s.items == nil {
		s.items = make(map[Item]bool)
	}

	_, ok := s.items[t]
	if !ok {
		s.items[t] = true
	}

	return *s
}

func (s *ItemSet) Clean(){
	s.items = make(map[Item]bool)
}

go get -u github.com/cheekybits/gennygenny -in set.go -out gen-set.go gen "Item=string,int"
set.gogen-set.go
// This file was automatically generated by genny.
// Any changes will be lost if this file is regenerated.
// see https://github.com/cheekybits/genny

// Package Set creates a StringSet data structure for the string type
package set

// StringSet the set of Strings
type StringSet struct {
	items map[string]bool
}

// Add adds a new element to the Set. Returns the Set.
func (s *StringSet) Add(t string) StringSet {
	s.items[t] = true
	return *s
}

// Clear removes all elements from the Set
func (s *StringSet) Clear() {
	(*s).items = make(map[string]bool)
}

// Delete removes the string from the Set and returns Has(string)
func (s *StringSet) Delete(item string) bool {
	ret := (*s).Has(item)
	if ret {
		delete((*s).items, item)
	}
	return ret
}

// Has returns true if the Set contains the string
func (s *StringSet) Has(item string) bool {
	return (*s).items[item]
}

// Strings returns the string(s) stored
func (s *StringSet) Strings() []string {
	items := []string{}
	for i := range s.items {
		items = append(items, i)
	}
	return items
}

// Package Set creates a IntSet data structure for the int type

// IntSet the set of Ints
type IntSet struct {
	items map[int]bool
}

// Add adds a new element to the Set. Returns the Set.
func (s *IntSet) Add(t int) IntSet {
	s.items[t] = true
	return *s
}

// Clear removes all elements from the Set
func (s *IntSet) Clear() {
	(*s).items = make(map[int]bool)
}

// Delete removes the int from the Set and returns Has(int)
func (s *IntSet) Delete(item int) bool {
	ret := (*s).Has(item)
	if ret {
		delete((*s).items, item)
	}
	return ret
}

// Has returns true if the Set contains the int
func (s *IntSet) Has(item int) bool {
	return (*s).items[item]
}

// Ints returns the int(s) stored
func (s *IntSet) Ints() []int {
	items := []int{}
	for i := range s.items {
		items = append(items, i)
	}
	return items
}
gennyItemSet **StringSetIntSetItem=string,int

同时也生成对应结构体方法,如果你想增加其他类型,只要编辑命令重新运行。

go generate
go generate
//go:generate genny -in=$GOFILE -out=gen-$GOFILE gen "Item=string,int"
genny
go generate
gen-set.go
go generate

3. 总结

gennygo generate