aboutsummaryrefslogtreecommitdiff
path: root/test/typeparam/stringer.go
blob: 81290d599ecda5af09e36d6fc7d42f0e587f36e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// run -gcflags=-G=3

// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Test method calls on type parameters

package main

import (
	"fmt"
	"reflect"
	"strconv"
)

// Simple constraint
type Stringer interface {
	String() string
}

func stringify[T Stringer](s []T) (ret []string) {
	for _, v := range s {
		ret = append(ret, v.String())
	}
	return ret
}

type myint int

func (i myint) String() string {
	return strconv.Itoa(int(i))
}

// Constraint with an embedded interface, but still only requires String()
type Stringer2 interface {
	CanBeStringer2() int
	SubStringer2
}

type SubStringer2 interface {
	CanBeSubStringer2() int
	String() string
}

func stringify2[T Stringer2](s []T) (ret []string) {
	for _, v := range s {
		ret = append(ret, v.String())
	}
	return ret
}

func (myint) CanBeStringer2() int {
	return 0
}

func (myint) CanBeSubStringer2() int {
	return 0
}

// Test use of method values that are not called
func stringify3[T Stringer](s []T) (ret []string) {
	for _, v := range s {
		f := v.String
		ret = append(ret, f())
	}
	return ret
}

func main() {
	x := []myint{myint(1), myint(2), myint(3)}

	got := stringify(x)
	want := []string{"1", "2", "3"}
	if !reflect.DeepEqual(got, want) {
		panic(fmt.Sprintf("got %s, want %s", got, want))
	}

	got = stringify2(x)
	if !reflect.DeepEqual(got, want) {
		panic(fmt.Sprintf("got %s, want %s", got, want))
	}

	got = stringify3(x)
	if !reflect.DeepEqual(got, want) {
		panic(fmt.Sprintf("got %s, want %s", got, want))
	}
}