Created
May 9, 2022 06:58
-
-
Save jqjk/aaffa980cf6847c6f3e5d224c3fcfd09 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func Map[T, U any](values []T, mapper func(T) U) []U { | |
var result []U | |
for _, v := range values { | |
result = append(result, mapper(v)) | |
} | |
return result | |
} | |
type Tuple[T, U any] struct { | |
X T | |
Y U | |
} | |
func New[T, U any](v1 T, v2 U) *Tuple[T, U] { | |
return &Tuple[T, U]{v1, v2} | |
} | |
type Number interface { | |
int | int32 | int64 | float32 | float64 | |
} | |
func Max[T Number](x, y T) T { | |
if x >= y { | |
return x | |
} | |
return y | |
} | |
func main() { | |
// 【TRY】マップ関数 | |
// https://docs.google.com/presentation/d/1TqCv_ECXBVGw1XOQ-v6rVRyiYGczl4yhDCJIhNLpzaQ/edit#slide=id.gc7f218b544_1_560 | |
var ss []string = Map([]int{10, 20}, func(n int) string { | |
return fmt.Sprintf("0x%x", n) | |
}) | |
fmt.Println(ss) | |
// 【TRY】Tuple型 | |
// https://docs.google.com/presentation/d/1TqCv_ECXBVGw1XOQ-v6rVRyiYGczl4yhDCJIhNLpzaQ/edit#slide=id.gc7f218b544_1_578 | |
var t *Tuple[int, string] = New(10, "hoge") | |
fmt.Println(t.X, t.Y) | |
// 【TRY】制約の無い型パラメタ | |
// https://docs.google.com/presentation/d/1TqCv_ECXBVGw1XOQ-v6rVRyiYGczl4yhDCJIhNLpzaQ/edit#slide=id.gc7f218b544_1_624 | |
fmt.Println(Max(10, 20)) // 20 | |
fmt.Println(Max(3.5, 2.5)) // 3.5 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment