Source file test/typeparam/min.go

     1  // run
     2  
     3  // Copyright 2021 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  package main
     8  
     9  import (
    10  	"fmt"
    11  )
    12  
    13  type Ordered interface {
    14  	~int | ~int64 | ~float64 | ~string
    15  }
    16  
    17  func min[T Ordered](x, y T) T {
    18  	if x < y {
    19  		return x
    20  	}
    21  	return y
    22  }
    23  
    24  func main() {
    25  	const want = 2
    26  	if got := min[int](2, 3); got != want {
    27  		panic(fmt.Sprintf("got %d, want %d", got, want))
    28  	}
    29  
    30  	if got := min(2, 3); got != want {
    31  		panic(fmt.Sprintf("want %d, got %d", want, got))
    32  	}
    33  
    34  	if got := min[float64](3.5, 2.0); got != want {
    35  		panic(fmt.Sprintf("got %d, want %d", got, want))
    36  	}
    37  
    38  	if got := min(3.5, 2.0); got != want {
    39  		panic(fmt.Sprintf("got %d, want %d", got, want))
    40  	}
    41  
    42  	const want2 = "ay"
    43  	if got := min[string]("bb", "ay"); got != want2 {
    44  		panic(fmt.Sprintf("got %d, want %d", got, want2))
    45  	}
    46  
    47  	if got := min("bb", "ay"); got != want2 {
    48  		panic(fmt.Sprintf("got %d, want %d", got, want2))
    49  	}
    50  }
    51  

View as plain text