Golang slices.MinFunc Function

The slices.MinFunc function in Golang is part of the slices package, introduced in Go 1.21 as part of the standard library. This function allows you to find the minimum element in a slice based on a custom comparison function. It is particularly useful when you need to determine the minimum value in a collection of elements that require a specific ordering criterion.

Table of Contents

  1. Introduction
  2. slices.MinFunc Function Syntax
  3. Examples
    • Basic Usage
    • Finding the Minimum in a Slice of Structs
    • Handling Custom Ordering for Complex Types
  4. Real-World Use Case Example
  5. Conclusion

Introduction

The slices.MinFunc function provides a flexible way to determine the minimum element in a slice according to a custom comparison function. This is especially useful when the default ordering (such as numeric or lexicographic) does not apply, or when working with complex types where the minimum element is defined by a specific attribute or combination of attributes.

slices.MinFunc Function Syntax

The syntax for the slices.MinFunc function is as follows:

func MinFunc[S ~[]E, E any](x S, cmp func(a, b E) int) E

Parameters:

  • x S: The slice from which to find the minimum element.
  • cmp func(a, b E) int: A custom comparison function that defines the ordering of elements. It should return:
    • A negative number if a should come before b.
    • Zero if a and b are considered equal.
    • A positive number if a should come after b.

Returns:

  • E: The minimum element in the slice, as determined by the custom comparison function.

Behavior:

  • Custom minimum element selection: The function iterates over the slice, using the custom comparison function to identify the element that should be considered the minimum according to the specified ordering.

Examples

Basic Usage

This example demonstrates how to use slices.MinFunc to find the minimum element in a slice of integers based on their absolute values.

Example

package main

import (
	"fmt"
	"slices"
)

func main() {
	// Define a slice of integers
	numbers := []int{-10, -20, 30, 40, -5}

	// Define a custom comparison function for absolute values
	absMin := func(a, b int) int {
		if abs(a) < abs(b) {
			return -1
		}
		if abs(a) > abs(b) {
			return 1
		}
		return 0
	}

	// Find the minimum value based on absolute value
	minValue := slices.MinFunc(numbers, absMin)

	// Print the result
	fmt.Println("Minimum value by absolute value:", minValue)
}

// Helper function to calculate absolute value
func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

Output:

Minimum value by absolute value: -5

Explanation:

  • The slices.MinFunc function uses the absMin comparison function to find the element with the minimum absolute value in the numbers slice. The minimum element, -5, is returned because it has the smallest absolute value.

Finding the Minimum in a Slice of Structs

This example shows how to use slices.MinFunc to find the minimum element in a slice of structs based on a specific field.

Example

package main

import (
	"fmt"
	"slices"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	// Define a slice of Person structs
	people := []Person{
		{"Alice", 30},
		{"Bob", 25},
		{"Charlie", 35},
	}

	// Define a custom comparison function to compare by Age
	byAge := func(a, b Person) int {
		return a.Age - b.Age
	}

	// Find the person with the minimum age
	youngestPerson := slices.MinFunc(people, byAge)

	// Print the result
	fmt.Printf("Youngest person: %s, Age: %d\n", youngestPerson.Name, youngestPerson.Age)
}

Output:

Youngest person: Bob, Age: 25

Explanation:

  • The slices.MinFunc function finds the Person with the minimum age in the people slice, which is "Bob" with an age of 25.

Handling Custom Ordering for Complex Types

This example demonstrates how slices.MinFunc can be used to find the minimum element in a slice of complex types where the comparison depends on multiple fields.

Example

package main

import (
	"fmt"
	"slices"
)

type Product struct {
	Name  string
	Price float64
	Rating float64
}

func main() {
	// Define a slice of Product structs
	products := []Product{
		{"Laptop", 1000.0, 4.5},
		{"Phone", 800.0, 4.7},
		{"Tablet", 600.0, 4.3},
	}

	// Define a custom comparison function to prioritize Rating, then Price
	byRatingAndPrice := func(a, b Product) int {
		if a.Rating != b.Rating {
			if a.Rating < b.Rating {
				return -1
			}
			return 1
		}
		return int(a.Price - b.Price)
	}

	// Find the product with the lowest rating and price
	lowestProduct := slices.MinFunc(products, byRatingAndPrice)

	// Print the result
	fmt.Printf("Lowest product: %s, Price: %.2f, Rating: %.1f\n", lowestProduct.Name, lowestProduct.Price, lowestProduct.Rating)
}

Output:

Lowest product: Tablet, Price: 600.00, Rating: 4.3

Explanation:

  • The slices.MinFunc function finds the product with the lowest rating and, in the case of a tie, the lowest price. In this case, the "Tablet" product is selected as the lowest product.

Real-World Use Case Example: Selecting the Stock with the Least Volatility

A practical use case for slices.MinFunc is selecting the stock with the least volatility from a portfolio based on custom criteria such as standard deviation of returns.

Example: Finding the Stock with the Least Volatility

package main

import (
	"fmt"
	"slices"
)

type Stock struct {
	Name       string
	Volatility float64
	Return     float64
}

func main() {
	// Define a slice of Stock structs
	stocks := []Stock{
		{"StockA", 0.15, 5.0},
		{"StockB", 0.10, 7.5},
		{"StockC", 0.20, 6.0},
	}

	// Define a custom comparison function to prioritize Volatility
	byVolatility := func(a, b Stock) int {
		if a.Volatility < b.Volatility {
			return -1
		}
		if a.Volatility > b.Volatility {
			return 1
		}
		return 0
	}

	// Find the stock with the least volatility
	leastVolatileStock := slices.MinFunc(stocks, byVolatility)

	// Print the result
	fmt.Printf("Least volatile stock: %s, Volatility: %.2f, Return: %.2f%%\n", leastVolatileStock.Name, leastVolatileStock.Volatility, leastVolatileStock.Return)
}

Output:

Least volatile stock: StockB, Volatility: 0.10, Return: 7.50%

Explanation:

  • The slices.MinFunc function selects "StockB" as the stock with the least volatility, making it the best choice based on the custom comparison criteria.

Conclusion

The slices.MinFunc function in Go is used for finding the minimum element in a slice based on custom comparison logic. It is particularly useful when dealing with complex types or when the criteria for determining the minimum element are non-standard. By using slices.MinFunc, you can efficiently select the most relevant element in your Go applications, ensuring that your custom criteria are met.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top