There are three new built-in functions in Go 1.21. Compared to the previous functions len, cap, delete, append, close, panic and so on, there are new changes, let’s take a look at them.

clear

clear has always been a function that everyone wanted, and this new function has been added to manipulate map and slice objects.

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

Write a program to test that it is indeed as described above:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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. First of all, the types supported are Ordered types, the types that can do + operations can be parameters, such as string types can also be, and secondly, it also supports indeterminate 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, Individual parameters are 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, i.e., at least 10
c := max(1, 2.0, 10)        // c == 10.0 (Floating-point arithmetic)
f := max(0, float32(x))     // float32
var s []string
_ = min(s...)               // Invalid: The slice parameter is not supported
t := max("", "foo", "bar")  // t == "foo" (Support string)

For the limit values of floating-point numbers, the following rules apply.

1
2
3
4
5
x        y    min(x, y)    max(x, y)
-0.0    0.0         -0.0          0.0    // Negative zero is less than positive zero
-Inf      y         -Inf            y    // Negative infinity is smaller than other numbers
+Inf      y            y         +Inf    // Positive infinity over 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 by byte.

Ref

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