DEV Community

Cover image for Golang 1.21 is here (Part 1)
Pedro Bertao
Pedro Bertao

Posted on • Updated on

Golang 1.21 is here (Part 1)

Golang 1.21 arrived on August 8th with some performance improvements, the addition of native packages, and functions that will enhance your code syntax and productivity in your daily work. Below, I've selected the a fews topics along with examples of how to use them. You can follow the complete change log here.

Let's start with the changes in the language itself, where utility functions were implemented: min, max and clear.

Min and Max

func main() {
    minInt := min(3, 2, 1, 4)
    minFloat := min(4.0, 2.0, 3.0, 1.0)
    minString := min("ab", "a", "abcd", "abc")

    fmt.Println("Min Integer:", minInt)
    fmt.Println("Min Float:", minFloat)
    fmt.Println("Min String:", minString)

    fmt.Println("==================")

    maxInt := max(4, 2, 3, 1)
    maxFloat := max(1.0, 4.0, 2.0, 3.0)
    maxString := max("a", "ab", "abc", "abcd")

    fmt.Println("Max Integer:", maxInt)
    fmt.Println("Max Float:", maxFloat)
    fmt.Println("Max String:", maxString)

}


Enter fullscreen mode Exit fullscreen mode

With the result

Min Integer: 1
Min Float: 1
Min String: a
==================
Max Integer: 4
Max Float: 4
Max String: abcd
Enter fullscreen mode Exit fullscreen mode

What's interesting is that with the addition of these two helper functions, Generics are used as input, and the type of the Generics is cmp.Ordered, which basically applies to all comparable types in the Go language.

You can see the Min-Max code here

Clear

According to the documentation,

The new clear function deletes all elements from a map or zeroes all elements of a slice.

func main() {
    intSlice := []int{1, 2, 3}
    floatSlice := []float64{1.0, 2.0, 3.0}
    stringSlice := []string{"a", "b", "c"}
    mapString := map[string]string{
        "Name": "Pedro",
        "Age":  "20",
    }

    clear(intSlice)
    clear(floatSlice)
    clear(stringSlice)
    clear(mapString)

    fmt.Println("Int Slice", intSlice)
    fmt.Println("Float Slice", floatSlice)
    fmt.Println("String Slice", stringSlice)
    fmt.Println("Map", mapString)

}
Enter fullscreen mode Exit fullscreen mode

With the result

Int Slice [0 0 0]
Float Slice [0 0 0]
String Slice [  ]
Map map[]
Enter fullscreen mode Exit fullscreen mode

As we can see, it not only clears the Slices, but also makes their sizes equal and replaces the values with default ones. In the case of the Map, after using the Clear function, it's as if it were an empty Map.

You can check the Clear code here

For the next parts I will cover some new cool Log, Cmp and Maps features that were added.]

Part two

Top comments (0)