more advanced usage of type constraints and tilde
tags: learning go programming
content
REMINDER
~works on go-type-constraint
examples
- we can define a type constraint that contains methods!
type Number interface {
~int64 | ~float64
}
type NumberStringer interface {
Number
fmt.Stringer
}- define a generic function with
NumberStringertype constraint:
func DescribeSum[T NumberStringer](a, b T) string {
return fmt.Printf("%s + %s = %v", a, b, a + b)
}- now to make some variables that could be passed in
DescribeSum:- the variable has to satisfy:
Number: underlying type isint64orfloat64- and
fmt.Stringer: has a methodString() string
- the variable has to satisfy:
type MyInt int64
func (m MyInt)String() string{
return fmt.Sprintf("MyInt(%v)", m)
}- now we can pass type
MyInttoDescribeSum:
myInt1 := MyInt(1)
myInt2 := MyInt(2)
fmt.Println(DescribeSum(myInt1, myInt2))
// prints: "MyInt(1) + MyInt(2) = MyInt(3)"
// notice: the sum is also type `MyInt`note
fmt.Stringeris just an interface withString()method- source code:
type Stringer interface {
String() string
}