notexOPENOverview
Notex/Languages/Emptying a Slice
01.07LESSON 07 OF 33 · 1 MIN READ

Emptying a Slice

Always free to read

Go 1.21 added a clear function that takes in a slice and sets all of the slice’s elements to their zero value. The length of the slice remains unchanged. The following code:

s := []string{"first", "second", "third"}
fmt.Println(s, len(s))
clear(s)
fmt.Println(s, len(s))

prints out:

[first second third] 3
[  ] 3

(Remember, the zero value for a string is an empty string ""!)

Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

Back to the library →
⌕
Search across the entire library ⌘ K