Tutorial by Examples

slice = append(slice, "hello", "world")
slice1 := []string{"!"} slice2 := []string{"Hello", "world"} slice := append(slice1, slice2...) Run in the Go Playground
If you need to remove one or more elements from a slice, or if you need to work with a sub slice of another existing one; you can use the following method. Following examples uses slice of int, but that works with all type of slice. So for that, we need a slice, from witch we will remove some ...
Slices have both length and capacity. The length of a slice is the number of elements currently in the slice, while the capacity is the number of elements the slice can hold before needing to be reallocated. When creating a slice using the built-in make() function, you can specify its length, and ...
If you wish to copy the contents of a slice into an initially empty slice, following steps can be taken to accomplish it- Create the source slice: var sourceSlice []interface{} = []interface{}{"Hello",5.10,"World",true} Create the destination slice, with: Length =...
Slices are the typical way go programmers store lists of data. To declare a slice variable use the []Type syntax. var a []int To declare and initialize a slice variable in one line use the []Type{values} syntax. var a []int = []int{3, 1, 4, 1, 5, 9} Another way to initialize a slice is with...
To filter a slice without allocating a new underlying array: // Our base slice slice := []int{ 1, 2, 3, 4 } // Create a zero-length slice with the same underlying array tmp := slice[:0] for _, v := range slice { if v % 2 == 0 { // Append desired values to slice tmp = append(tmp, ...
The zero value of slice is nil, which has the length and capacity 0. A nil slice has no underlying array. But there are also non-nil slices of length and capacity 0, like []int{} or make([]int, 5)[5:]. Any type that have nil values can be converted to nil slice: s = []int(nil) To test whether a...

Page 1 of 1