Source file test/typeparam/smallest.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 | ~int8 | ~int16 | ~int32 | ~int64 |
    15  		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
    16  		~float32 | ~float64 |
    17  		~string
    18  }
    19  
    20  func Smallest[T Ordered](s []T) T {
    21  	r := s[0] // panics if slice is empty
    22  	for _, v := range s[1:] {
    23  		if v < r {
    24  			r = v
    25  		}
    26  	}
    27  	return r
    28  }
    29  
    30  func main() {
    31  	vec1 := []float64{5.3, 1.2, 32.8}
    32  	vec2 := []string{"abc", "def", "aaa"}
    33  
    34  	want1 := 1.2
    35  	if got := Smallest(vec1); got != want1 {
    36  		panic(fmt.Sprintf("got %d, want %d", got, want1))
    37  	}
    38  	want2 := "aaa"
    39  	if got := Smallest(vec2); got != want2 {
    40  		panic(fmt.Sprintf("got %d, want %d", got, want2))
    41  	}
    42  }
    43  

View as plain text