Member-only story

GO new feature: no need to loop delete map elements

Beck Moulton
2 min readJun 28, 2023

--

As early as October 2022, RSC has a proposal: spec: add clear (x) builtin, to clear map, zero content of slice) , the main reason is to kill code like this:

for k := range m {
delete(m, k)
}

The Go tip version already has a clear function. Its function signature is as follows:

func clear[T ~[]Type | ~map[Type]Type1](t T)

Clear clears the value of a slice or map type, sets all its underlying elements to zero values, and keeps its slice length and capacity unchanged.

In summary, clear function can solve the following types of problems:

  • When a slice needs to be emptied, it used to be necessary to use methods such as s = s [: 0] or s = nil , which are not intuitive and consistent, and may lead to memory leaks or performance degradation. Use clear (s) to complete the emptying operation more concisely and efficiently, while preserving the underlying memory.
  • When a map needs to be emptied, it used to be necessary to use methods such as for k: = range m {delete (m, k) } or m = nil , which are not elegant and safe enough, and may lead to memory waste or race conditions. Using clear (m) makes emptying easier and safer.

In short, you can use the clear function when you need to clear the value of a slice or map type. However, the following points should be noted:

  • clear function can only accept values of slice or map type as…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet