현재 3권의 신간들인 Go Optimizations 101, Go Details & Tips 101Go Generics 101이 출간되어 있습니다. Leanpub 서점에서 번들을 모두 구입하시는 방법이 비용 대비 효율이 가장 좋습니다.

Go에 대한 많은 정보들과 Go 101 책들의 최신 소식을 얻으시려면 Go 101 트위터 계정인 @Go100and1을 팔로잉 해주세요.

Generics

Before Go 1.18, Go only supported built-in generics. Since Go 1.18, Go also supports custom generics. This article only introduces built-in generics.

Go built-in generic types are supported through first-class citizen composite types. We can use composite types to create infinite custom types by using the composite types. This article will show some type composition examples and explain how to read these composited types.

Type Composition Examples

Type compositions in Go are designed very intuitive and easy to interpret. It is hardly to get lost in understanding Go composite types, even if for some very complex ones. The following will list several type composition examples, from simpler ones to more complex ones.

Let's view an simple composite type literal.
[3][4]int

When interpreting a composite type, we should look at it from left to right. The [3] on the left in the above type literal indicates that this type is an array type. The whole right part following the [4]int is another array type, which is the element type of the first array type. The element type of the element type (an array type) of the first array type is built-in type int. The first array type can be viewed as a two-dimensional array type.

An example on using this two-dimensional array type.
package main

import (
	"fmt"
)

func main() {
	matrix := [3][4]int{
		{1, 0, 0, 1},
		{0, 1, 0, 1},
		{0, 0, 1, 1},
	}

	matrix[1][1] = 3
	a := matrix[1] // type of a is [4]int
	fmt.Println(a) // [0 3 0 1]
}

Similarly,

Let's view another type.
chan *[16]byte

The chan keyword at the left most indicates this type is a channel type. The whole right part *[16]byte, which is a pointer type, denotes the element type of this channel type. The base type of the pointer type is [16]byte, which is an array type. The element type of the array type is byte.

An example on using this channel type.
package main

import (
	"fmt"
	"time"
	"crypto/rand"
)

func main() {
	c := make(chan *[16]byte)

	go func() {
		// Use two arrays to avoid data races.
		var dataA, dataB = new([16]byte), new([16]byte)
		for {
			_, err := rand.Read(dataA[:])
			if err != nil {
				close(c)
			} else {
				c <- dataA
				dataA, dataB = dataB, dataA
			}
		}
	}()

	for data := range c {
		fmt.Println((*data)[:])
		time.Sleep(time.Second / 2)
	}
}

Similarly, type map[string][]func(int) int is a map type. The key type of this map type is string. The remaining right part []func(int) int denotes the element type of the map type. The [] indicates the element type is a slice type, whose element type is a function type func(int) int.

An example on using the just explained map type.
package main

import "fmt"

func main() {
	addone := func(x int) int {return x + 1}
	square := func(x int) int {return x * x}
	double := func(x int) int {return x + x}

	transforms := map[string][]func(int) int {
		"inc,inc,inc": {addone, addone, addone},
		"sqr,inc,dbl": {square, addone, double},
		"dbl,sqr,sqr": {double, double, square},
	}

	for _, n := range []int{2, 3, 5, 7} {
		fmt.Println(">>>", n)
		for name, transfers := range transforms {
			result := n
			for _, xfer := range transfers {
				result = xfer(result)
			}
			fmt.Printf(" %v: %v \n", name, result)
		}
	}
}

Below is a type which looks some complex.
[]map[struct {
	a int
	b struct {
		x string
		y bool
	}
}]interface {
	Build([]byte, struct {x string; y bool}) error
	Update(dt float64)
	Destroy()
}

Let's read it from left to right. The starting [] at the left most indicates this type is a slice type. The following map keyword shows the element type of the slice type is a map type. The struct type denoted by the struct literal enclosed in the [] following the map keyword is the key type of the map type. The element type of the map type is an interface type which specifies three methods. The key type, a struct type, has two fields, one field a is of int type, and the other field b is of another struct type struct {x string; y bool}.

Please note that the second struct type is also used as one parameter type of one method specified by the just mentioned interface type.

To get a better readability, we often decompose such a type into multiple type declarations. The type alias T declared in the following code and the just explained type above denote the identical type.
type B = struct {
	x string
	y bool
}

type K = struct {
	a int
	b B
}

type E = interface {
	Build([]byte, B) error
	Update(dt float64)
	Destroy()
}

type T = []map[K]E

Built-in Generic Functions

Besides the built-in generics for composite types, there are several built-in functions which also support generics. Such as the built-in len function can be used to get the length of values of arrays, slices, maps, strings and channels. Generally, the functions in the unsafe standard package are also viewed as built-in functions. The built-in generic functions have been introduced in previous articles,

Custom Generics

Since version 1.18, Go has already supported custom generics. Please read the Go Generics 101 book to get how to use custom generics.


Index↡

The Go 101 프로젝트는 Github 에서 호스팅됩니다. 오타, 문법 오류, 부정확한 표현, 설명 결함, 코드 버그, 끊어진 링크와 같은 모든 종류의 실수에 대한 수정 사항을 제출하여 Go 101을 개선을 돕는 것은 언제나 환영합니다.

주기적으로 Go에 대한 깊이 있는 정보를 얻고 싶다면 Go 101의 공식 트위터 계정인 @go100and1을 팔로우하거나 Go 101 슬랙 채널에j가입해주세요.

이 책의 디지털 버전은 아래와 같은 곳을 통해서 구매할 수 있습니다.
Go 101의 저자인 Tapir는 2016년 7월부터 Go 101 시리즈 책들을 집필하고 go101.org 웹사이트를 유지 관리하고 있습니다. 새로운 콘텐츠는 책과 웹사이트에 수시로 추가될 예정입니다. Tapir는 인디 게임 개발자이기도 합니다. Tapir의 게임을 플레이하여 Go 101을 지원할 수도 있습니다. (안드로이드와 아이폰/아이패드용):
  • Color Infection (★★★★★), 140개 이상의 단계로 이루어진 물리 기반의 캐주얼 퍼즐 게임
  • Rectangle Pushers (★★★★★), 2가지 모드와 104개 이상의 단계로 이루어진 캐주얼 퍼즐 게임
  • Let's Play With Particles, 세가지 미니 게임이 있는 캐주얼 액션 게임
페이팔을 통한 개인 기부도 환영합니다.

색인: