当前位置:网站首页>golang clean a slice

golang clean a slice

2022-06-24 03:34:00 大魔法师云中君

To remove all elements, set the slice to nil:
	a := []string{
    "A", "B", "C", "D", "E"}
	a = nil
	fmt.Println(a, len(a), cap(a)) // [] 0 0
This will release the underlying array to the garbage collector
	(assuming there are no other references).

Keep allocated memory
	To keep the underlying array, slice the slice to zero length:
		a := []string{
    "A", "B", "C", "D", "E"}
		a = a[:0]
		fmt.Println(a, len(a), cap(a)) // [] 0 5
	If the slice is extended again, the original data reappears:
		fmt.Println(a[:2]) // [A B]
原网站

版权声明
本文为[大魔法师云中君]所创,转载请带上原文链接,感谢
https://wkisme.blog.csdn.net/article/details/125433179