# 聊聊 Go 中完全木有排面的元组

## 天生我材必有用

### 元组的一技之长

``````type Point struct{ X, Y int }

func PrintPoint1() {
point := Point{1, 2}

x, y := point.X, point.Y

fmt.Printf("point at { x: %d, y: %d }\n", x, y)
}

// output: point at { x: 1, y: 2 }``````

``````func PrintPoint2() {
point := (1, 2)

x, y := point

fmt.Printf("point at { x: %d, y: %d }\n", x, y)
}``````

### 实际场景

``````    bus := new(EventBus[int])

cancel, err := bus.Subscribe(func(event string, i int) bool {
// do something
return true
}, On("put")) // 订阅 put 事件

//...

bus.Emit("put", 0) // 触发事件``````

``bus := new(EventBus[Tuple[User, Blog]])``

## 元组的3种实现

### 函数多返回值

``````func PrintPoint2() {
point := func() (int, int) {
return 1, 2
}

x, y := point()

fmt.Printf("point at { x: %d, y: %d }\n", x, y)
}``````

### 泛型函数

``````type Pair[L, R any] func() (L, R)

func TwoTuple[T1, T2 any](v1 T1, v2 T2) Pair[T1, T2] {
return func() (T1, T2) {
return v1, v2
}
}

func PrintPoint2() {
point := TwoTuple(1, 2)

x, y := point()

fmt.Printf("point at { x: %d, y: %d }\n", x, y)
}``````

``````// ...

func (p Pair[L, R]) Right() R {
_, r := p()
return r
}

// ...

func PrintPoint2() {
point := TwoTuple(1, 2)

x, y := point()

fmt.Printf("point at { x: %d, y: %d }\n", x, y)

point2 := TwoTuple(1, 2.33)

fmt.Printf("point at { y: %f }\n", point2.Right())
}``````

### 泛型结构体

``````type Tuple2[T1, T2 any] struct {
V1 T1
V2 T2
}``````

(=￣ω￣=)··· 暂无内容！

5

1

9

1