개요
예제
- 코드
-
package main
import "fmt"
type Test[T int | string] struct {
t1 T
t2 T
}
func (this Test[T]) Add() T {
return this.t1 + this.t2
}
func test1[T comparable](arg T) {
fmt.Printf("%T\n", arg)
}
func test2[T int | string](arg1, arg2 T) {
println(arg1 + arg2)
}
type Type1 interface {
int | string
}
func test3[T Type1](arg T) {
fmt.Printf("%T\n", arg)
}
func test4[T1 int, T2 string](arg1 T1, arg2 T2) {
fmt.Printf("%T, %T\n", arg1, arg2)
}
func main() {
println(Test[int]{t1: 1, t2: 2}.Add())
println(Test[string]{t1: "a", t2: "b"}.Add())
println()
test1(int(0))
test1(string(""))
println()
test2(1, 2)
test2("abc", "def")
println()
test3(int(0))
test3(string(""))
println()
test4(1, "b")
test4(2, "a")
}
- 실행 결과
-
3
ab
int
string
3
abcdef
int
string
int, string
int, string