Is there a built in min function for a slice of int arguments or a variable number of int arguments in golang?

Is there a built in function that returns the minimum of a slice of int arguments:

func MinIntSlice(v []int) (m int) {
    if len(v) > 0 {
        m = v[0]
    }
    for i := 1; i < len(v); i++ {
        if v[i] < m {
            m = v[i]
        }
    }
    return
}

OR the minimum of a variable number of int arguments:

func MinIntVarible(v1 int, vn ...int) (m int) {
    m = v1
    for i := 0; i < len(vn); i++ {
        if vn[i] < m {
            m = vn[i]
        }
    }
    return
}

If not, is the best “convention” simply to create a package that contains helpers like this?

Edit: This answer is out of date. There are now built-in functions min and max in Go as of 1.21. See Jonas’ answer.

There is no built-in for this.

If you need this functionality only in one package you can write an un-exported function (e.g. minIntSlice).

If you need this functionality in multiple packages you can create a package and put similar functions there. You should consider making this package internal (https://golang.org/s/go14internal).

A few suggestions how to improve your code:

  1. MinIntSlice will return 0 for an empty slice. However 0 is a valid min element as well. I think calling panic on an empty slice is a better option.

  2. Use range loop:

     for i, e := range v {
         if i==0 || e < m {
             m = e
         }
     }
    

by not giving the index of value it will give you the minimum value 0, which may not be present in given values, so you also have to apply condition on index.

3

As of Go 1.21 there are now built-in functions to get the max and min for a given number of arguments as well as a new slices package to achieve the same for slices.

https://go.dev/ref/spec#Min_and_max

min(2, -5, 8, 1.2) // Result: -5
max(2, -5, 8, 1.2) // Result: 8

For slices, use the slices package:
https://pkg.go.dev/slices

import "slices"
x := []float64{2, -5, 8, 1.2}
slices.Min(x) // Result: -5
slices.Max(x) // Result: 8

1

As @kostya correctly stated there is no built-in min or max function in Golang.

However, I would suggest a slightly different solution:

func MinMax(array []int) (int, int) {
    var max int = array[0]
    var min int = array[0]
    for _, value := range array {
        if max < value {
            max = value
        }
        if min > value {
            min = value
        }
    }
    return min, max
}

By that the problem of an empty slice is solved: a runtime error shows up (index out of range) and the max value is for free. 🙂

    min := s[0]
    for i :=1; i < len(s); i++ {
        if min > s[i] {
            min = s[i]
        }
    }

min > s[i]? min = s[i] : min

1

if you don’t care about input array

import . "sort"
func MinIntSlice(v []int){
    Ints(v)
    return z[0]
}

func MaxIntSlice(v []int){
    Ints(v)
    return z[len(v)-1]
}
// and MinMax version
func MinMax(v []int)(int,int){
    Ints(v)
    return z[0],z[len(v)-1]
}

This package contains some implementations of Min and Max functions for separate values or slices. After go get it can be used like:

import (
    "fmt"
    "<Full URL>/go-imath/ix" // Functions for int type
)
...
fmt.Println(ix.Min(100, 152)) // Output: 100
fmt.Println(ix.Mins(234, 55, 180)) // Output: 55
fmt.Println(ix.MinSlice([]int{2, 29, 8, -1})) // Output: -1

There is no function for such operation in the standard packages.

However, the gonum library offers the functions floats.Min(x) and floats.Max(x) (and other interesting functions for manipulation of numerical data).

Usage:

package main

import (
    "fmt"
    "gonum.org/v1/gonum/floats"
)

func main() {
    x := []float64{1, 6, 9, -3, -5}
    minX := floats.Min(x)
    maxX := floats.Max(x)
    fmt.Printf("Min: %f, max %fn", minX, maxX)
}

Results:

Min: -5.000000, max 9.000000

For huge slices containing millions of items (for example a 25 megapixel image as []int) you can get significant performance gains by calculating min/max in chunks:

func GetMinMax(data []int) (int, int) {
    minVal := data[0]
    maxVal := data[0]
    for i := range data {
        if data[i] < minVal {
            minVal = data[i]
        }

        if data[i] > maxVal {
            maxVal = data[i]
        }
    }

    return minVal, maxVal
}

func GetMinMaxConcurrent(data []int) (int, int) {
    numChan := make(chan int)

    numChunks := runtime.NumCPU()
    chunkSize := len(data) / numChunks

    // Process
    var wg sync.WaitGroup
    for i := 0; i < numChunks; i++ {
        wg.Add(1)
        go func(i, chunkSize int, numChan chan int) {
            startIndex := i * chunkSize
            endIndex := startIndex + chunkSize
            if endIndex > len(data) {
                endIndex = len(data)
            }

            minVal, maxVal := GetMinMax(data[startIndex:endIndex])
            numChan <- minVal
            numChan <- maxVal
            wg.Done()
        }(i, chunkSize, numChan)
    }

    // Collect results
    resultsChan := make(chan int)
    defer close(resultsChan)

    go func(numChan, resultsChan chan int) {
        arr := make([]int, 0)
        for num := range numChan {
            arr = append(arr, num)
        }
        minVal, maxVal := GetMinMax(arr)
        resultsChan <- minVal
        resultsChan <- maxVal
    }(numChan, resultsChan)

    wg.Wait()
    close(numChan) // needed so results routine can return

    return <-resultsChan, <-resultsChan
}

This code is not performant for small slices, only use if your slice is big enough to benefit from processing chunks concurrently.

With sorting it can be shorter:

func MinIntSlice(v []int) int {
  sort.Ints(v)
  return v[0]
}

func MaxIntSlice(v []int) int {
  sort.Ints(v)
  return v[len(v)-1]
}

But don’t forget to modify it for zero length slices on your taste.

4

Using @kostya’s answer

  1. Use range loop:

    for i, e := range v {
        if i==0 || e < m {
            m = e
        }
    }
    

by not giving the index of value it will give you the minimum value 0, which may not be present in given values

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật