Member-only story
GO new feature: no need to loop delete map elements
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]
ors = nil
, which are not intuitive and consistent, and may lead to memory leaks or performance degradation. Useclear (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) }
orm = nil
, which are not elegant and safe enough, and may lead to memory waste or race conditions. Usingclear (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…