10 examples of 'golang create empty slice' in Go

Every line of 'golang create empty slice' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Go code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
260func (pac *Package) newSlice(elemType gcc.Type) *Slice {
261 return &Slice{elementType: pac.declareEqualType(elemType)}
262}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

415func (v *BaseKParserVisitor) VisitSlice(ctx *SliceContext) interface{} {
416 return v.VisitChildren(ctx)
417}
39func createSliceOperator(args ...interface{}) []interface{} {
40 return args
41}
633func sliceAddIfNotExists(slice []string, value string) []string {
634 if !sliceContains(slice, value) {
635 slice = append(slice, value)
636 }
637 return slice
638}
63func jitSliceToBytes(slice C.wasmjit_slice_t) []byte {
64 return C.GoBytes((unsafe.Pointer)(slice.data), C.int(slice.len))
65}
191func (matrix *DenseMatrix) Slice(rfrom, rto, cfrom, cto int) Matrix {
192 m := *matrix
193 m.rowOffset += rfrom
194 m.rows = rto - rfrom
195 m.colOffset += cfrom
196 m.cols = cto - cfrom
197 // crop tmp vectors
198 m.initTmp()
199 return &m
200}
175func (matrix *SparseInt32Matrix) SLICE(rfrom, rto, cfrom, cto int) *SparseInt32Matrix {
176 m := *matrix
177 m.rowOffset += rfrom
178 m.rows = rto - rfrom
179 m.colOffset += cfrom
180 m.cols = cto - cfrom
181 // crop tmp vectors
182 m.initTmp()
183 return &m
184}
24func Slice(arr []byte, count int) [][]byte {
25
26 sliceCount := len(arr) / count
27 result := make([][]byte, sliceCount)
28
29 for i := 0; i < sliceCount; i++ {
30 start := i * count
31 end := i*count + count
32
33 result[i] = arr[start:end]
34 }
35
36 return result
37}
11func sliceDemo2() {
12 slice1 := []int{1, 2, 3}
13 printSlice(slice1)
14 // slice1[len(slice1)] = 4 // 虽然是不定长的切片,但是一旦赋值容量就固定了,这里会报错
15
16 //指定容量
17 slice1 = make([]int, 3, 5) // 3 是长度 5 是容量
18 printSlice(slice1)
19
20 // slice1[len(slice1)] = 4 // 还是会报错,虽然容量是 5 ,但是数组长度是3,这里是以长度为准,而不是容量
21
22 //使用append来追加元素,append很常用
23 slice1 = append(slice1, 4)
24 printSlice(slice1)
25
26 slice1 = append(slice1, 5)
27 slice1 = append(slice1, 6) // 到这里长度超过了容量,容量自动翻倍为 5*2
28 printSlice(slice1)
29
30 // 上面容量自动翻倍的过程可以看作和下面一致
31 slice1 = make([]int, 3, 5) // 3 是长度 5 是容量
32 slice1 = append(slice1, 4)
33 slice1 = append(slice1, 5)
34
35 // 长度不变,容量自动翻倍为 5*2
36 slice2 := make([]int, len(slice1), (cap(slice1))*2)
37
38 /* 拷贝 slice1 的内容到 slice2 */
39 copy(slice2, slice1) // 注意是后面的拷贝给前面
40 slice2 = append(slice2, 6)
41 printSlice(slice2)
42
43}
52func filledByteSlice2D(length, innerLen uint64) [][]byte {
53 b := make([][]byte, length)
54 for i := uint64(0); i < length; i++ {
55 b[i] = make([]byte, innerLen)
56 }
57 return b
58}

Related snippets