do you know? Go adds three new built-in functions

Original link: https://colobu.com/2023/05/28/go1-21-whats-new-builtin/

In Go 1.21, three built-in functions have been added. Compared with the previous functions such as len , cap , delete , append , close , panic , etc., there are new changes. Let’s take a look.

clear

clear has always been a function that everyone wants. This new function is used to operate map and slice objects:


1

func clear[T ~[]Type | ~ map [Type]Type1](t T)
  • For the map object: the clear function clears all elements of the map object
  • For slice objects: The clear function sets all elements to the zero value of the element type, with the same length and capacity

Write a program to test, it is indeed as above:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

func testClear() {
m := map [ float64 ] bool {100 : true , 1000 : true , math.NaN(): true , math.NaN(): true }
delete (m, math. NaN())
fmt.Printf( “before clear, m len: %d\n” , len (m))
clear(m)
fmt.Printf( “after clear, m len: %d\n” , len (m))
s := make ([] float64 , 0 , 1024 *1024 )
for i := 0 ; i < 10 ; i++ {
s = append (s, float64 (i))
}
fmt.Printf( “before clear, s len: %d, s cap: %d\n” , len (s), cap (s))
clear(s)
fmt.Printf( “after clear, s len: %d, s cap: %d\n” , len (s), cap (s))
fmt. Println(s)
}

Run gotip run main.go and output the result


1
2
3
4
5

before clear, m len : 4
after clear, m len : 0
before clear, s len : 10 , s cap : 1048576
after clear, s len : 10 , s cap : 1048576
[0 0 0 0 0 0 0 0 0 0 ]

min and max functions

These two newly added functions for finding the maximum and minimum values ​​are much more convenient than math.Max ​​and math.Min .
Firstly, the supported type is the Ordered type, and all types that can do + operations can be used as parameters, such as the string type, and secondly, it also supports variable-length parameters, which is convenient to use.

For example the following call:


1
2
3
4
5
6
7
8
9

var x, y int
m := min(x) // m == x, a single parameter is fine!
m := min(x, y) // m is the smallest of x and y
m := max(x, y, 10 ) // m is the largest of x, y, 10, that is, at least 10
c := max (1 , 2.0 , 10 ) // c == 10.0 (float)
f := max (0 , float32 (x)) // float32 type
var s [] string
_ = min(s…) // invalid: slice parameter not supported
t := max( “” , “foo” , “bar” ) // t == “foo” (supports string type)

For the limit value of floating-point numbers, the following rules apply:


1
2
3
4
5
6

xy min(x, y) max(x, y)
0.0 0.00.0 0.0 // Negative zero is less than positive zero
Inf y – Inf y // negative infinity is less than other numbers
+ Inf yy + Inf // positive infinity greater than other numbers
NaN y NaN NaN // As long as one parameter is NaN , the return of these two functions will be NaN

Strings are compared byte by byte.

This article is transferred from: https://colobu.com/2023/05/28/go1-21-whats-new-builtin/
This site is only for collection, and the copyright belongs to the original author.