xxxxxxxxxx
// Use of golang slice
func main() {
// initialise the slice with 10 zero ints
slice := make([]int, 10)
// fillup with random ints
fillSliceWithRand(slice)
// prints the slice
print(slice)
// passes the slice by reference and reverse the slice
reverse(slice)
// prints the slice again
print(slice)
}
// reverse method reverse the slice
func reverse(a []int) {
l := len(a)
for i := 0; i < l/2; i ++ {
x := a[l-i-1]
a[l-i-1] = a[i]
a[i] = x
}
}
// print method prints all ints of the slice
func print(a []int) {
for _, v := range a {
fmt.Printf("%d ", v)
}
fmt.Println()
}
// fillSliceWithRand method fills the slice with random ints
func fillSliceWithRand(a []int) {
for i := 0; i < len(a); i++ {
a[i] = rand.Intn(100)
}
}
/**
## Slice in golang
- Slices hold references to an underlying array, and if you
assign one slice to another, both refer to the same array.
- If a function takes a slice argument, changes it makes to
the elements of the slice will be visible to the caller,
analogous to passing a pointer to the underlying array.
**/
xxxxxxxxxx
package main
import (
"fmt"
)
func main() {
var slice = []int{1, 2, 3, 4, 5}
var store = make([]int, 3)
push := append(slice, 6, 7, 8, 9)
copy(store, slice)
fmt.Println("before append value", slice)
fmt.Println("after append value", push)
fmt.Println("render value all value exist", push[:])
fmt.Println("render value after second value", push[2:])
fmt.Println("render value before third index", push[:3])
fmt.Println("render value start from zero and last value before second index", push[0:2])
fmt.Println("merge slice value", store)
fmt.Println("read size slice", len(slice))
fmt.Println("read capacity slice", cap(slice))
}
xxxxxxxxxx
// Program to create a slice and print its elements
package main
import "fmt"
func main() {
// declaring slice variable of type integer
numbers := []int{1, 2, 3, 4, 5}
// print the slice
fmt.Println("Numbers: ", numbers)
}