more advanced usage of type constraints and tilde

tags: learning go programming

content

REMINDER

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 NumberStringer type 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 is int64 or float64
      • and fmt.Stringer: has a method String() string
type MyInt int64
func (m MyInt)String() string{
	return fmt.Sprintf("MyInt(%v)", m)
}
  • now we can pass type MyInt to DescribeSum:
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.Stringer is just an interface with String() method
  • source code:
type Stringer interface {
	String() string
}

up

down

reference