GO使用泛型

203 阅读1分钟

目前的版本中 go 是不支持使用泛型的,不过泛型已经在 go 的草案中了,可以通过手动编译go2go 来体验。

  1. 先从 github 上把 go 的项目拉下来 git clone https://github.com/golang/go.git

  2. 然后切换到分支git checkout dev.go2go

  3. 编译cd src && ./all.bash 编译要求首先已经安装了 go 的正式版本

  4. 新建一个泛型的main.go2文件

    package main
    
    import "fmt"
    type Stack[E any] []E
    
    func (s *Stack[E]) Push(e E) {
    	*s = append(*s, e)
    }
    
    func (s *Stack[E]) Pop() (E, bool) {
    	l := len(*s)
    	if l == 0 {
    		var zero E
    		return zero, false
    	}
    	r := (*s)[l - 1]
    	*s = (*s)[:l - 1]
    	return r, true
    }
    
    func (s *Stack[E]) IsEmpty() bool {
    	return len(*s) == 0
    }
    
    func (s *Stack[E]) Len() int {
    	return len(*s)
    }
    
    func main() {
    	var s Stack[int]
    	for i := 0; i < 5; i++ {
    		s.Push(i)
    	}
    	fmt.Println(s)
    }
    
    
  5. 运行,go2go 作为 go 的一个 tool

    go tool go2go run main.go2

    打印: [0 1 2 3 4]

更多泛型用法可以查看仓库的/test/gen目录