max 函数

// The max built-in function returns the largest value of a fixed number of
// arguments of [cmp.Ordered] types. There must be at least one argument.
// If T is a floating-point type and any of the arguments are NaNs,
// max will return NaN.
func max[T cmp.Ordered](x T, y ...T) T

内置函数 max 返回固定数量的 [cmp.Ordered] 类型参数中的最大值。该接口要求至少提供有一个参数。如果 T 是浮点类型,或有任意一个参数是 NaN,那max 将返回 NaN

使用示例:

package main

import "fmt"

func main() {
	a, b, c := 2, 7, 3
	maxV := max(a, b, c)
	fmt.Println(maxV) // 7

	d, e, f := 2.0, 4.3, 5.2
	maxF := max(d, e, f)
	fmt.Println(maxF) // 5.2

	g, h, i := "aaa", "abc", "abd"
	maxS := max(g, h, i)
	fmt.Println(maxS) // abd
}

min 函数

// The min built-in function returns the smallest value of a fixed number of
// arguments of [cmp.Ordered] types. There must be at least one argument.
// If T is a floating-point type and any of the arguments are NaNs,
// min will return NaN.
func min[T cmp.Ordered](x T, y ...T) T

内置函数 min 返回固定数量的 [cmp.Ordered] 类型参数中的最小值。该接口要求至少提供有一个参数。如果 T 是浮点类型,或有任意一个参数是 NaN,那min 将返回 NaN

使用示例:

package main

import "fmt"

func main() {
	a, b, c := 2, 7, 3
	maxV := min(a, b, c)
	fmt.Println(maxV) // 2

	d, e, f := 2.1, 4.3, 5.2
	maxF := min(d, e, f)
	fmt.Println(maxF) // 2.1

	g, h, i := "aaa", "abc", "abd"
	maxS := min(g, h, i)
	fmt.Println(maxS) // aaa
}

clear 函数

// The clear built-in function clears maps and slices.
// For maps, clear deletes all entries, resulting in an empty map.
// For slices, clear sets all elements up to the length of the slice
// to the zero value of the respective element type. If the argument
// type is a type parameter, the type parameter's type set must
// contain only map or slice types, and clear performs the operation
// implied by the type argument.
func clear[T ~[]Type | ~map[Type]Type1](t T)

内置函数 clear 用于清空映射和切片:

  • 对于 mapsclear 删除所有元素,返回一个空map。
  • 对于 slicesclear 将切片长度内的所有元素设置为各自元素类型的零值。
  • 如果参数类型是类型参数,类型参数的类型集必须只包含mapslice类型。

使用示例:

package main

import "fmt"

func main() {
	a := []int{1, 3, 4, 6}
	clear(a)
	fmt.Printf("len(a): %d \t elem: %v\n", len(a), a) // len(a): 4 	 elem: [0 0 0 0]

	b := []string{"aaa", "bbb", "ccc"}
	clear(b)
	fmt.Printf("len(b): %d \t elem: %v\n", len(b), b) // len(b): 3 	 elem: [  ]

	c := map[string]interface{}{"name": "孟斯特", "age": 30}
	clear(c)
	fmt.Printf("len(c): %d \t elem: %v\n", len(c), c) // len(c): 0 	 elem: map[]
}

孟斯特

声明:本作品采用署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)进行许可,使用时请注明出处。
Author: mengbin
blog: mengbin
Github: mengbin92
cnblogs: 恋水无意