当前位置:网站首页>Create a slice slice pit using the make method

Create a slice slice pit using the make method

2022-06-12 14:01:00 Running SnaiL_

First look at the following code

package main

import "fmt"

func main() {
    
	ints := make([]int, 3)
	ints = append(ints, 1)
	fmt.Println(ints)
}

The result of printing is

[0 0 0 1]

Because use Built in functions make([]type, len) establish slice when len The parameter is treated as the initial length , Will be initialized automatically , The type we use here is int, So the initialization value is 0 , If it's a pointer type Then the initialization value is nil.

It's not that what I imagined at the beginning was just to slice A built-in length , The added elements will be automatically added from 0 Start , This pit is mainly used by me java List The idea of golang in .

原网站

版权声明
本文为[Running SnaiL_]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121353277744.html