golang tutorial - Golang Slice | Go slicing - golang - go programming language - google go - go language - go program - google language



Golang Slicing

  • Go Slice is an abstraction over Go Array.
  • To overcome the Go Array limitations, slicing option comes into the picture. It allows to define type of variables that can hold several data items of the same kind but it do not provide any inbuilt method to increase size of it dynamically or get a sub-array of its own.
  • It provides many utility functions required for an Array and is widely used in Go programming.

Defining a slice

var Marks   []int /* a slice of unspecified size */
/* Marks  == []int{0,0,0,0,0}*/
Marks  = make([]int,6,6) /* a slice of length 6 and capacity 6*/
click below button to copy the code. By - golang tutorial - team

len() and cap() functions

  • Slice is an abstraction over array. It actually uses array as an underlying structure.
  • len() function returns the number of elements presents in the slice
  • cap() function returns the max capacity of slice as how many elements it can be accommodate
package main

import "fmt"

func main() {
   var Marks   = make([]int,3,5)
   
   SliceDetails(Marks  )
}

func SliceDetails(x []int){
   fmt.Printf("length=%d capacity=%d sliceDetails=%v\n",len(x),cap(x),x)
}
click below button to copy the code. By - golang tutorial - team
  • When the above code is compiled and executed, it produces the following result:
length =3 capacity =5 sliceDetails =[0 0 0]
click below button to copy the code. By - golang tutorial - team

Nil slice

  • If a slice is declared with no inputs the by default, it is initialized as nil. Its length and capacity are zero
package main

import "fmt"

func main() {
   var Marks   []int
   
   SliceDetails(Marks)
   
   if(Marks   == nil){
      fmt.Printf("slice is nil")
   }
}

func SliceDetails(x []int){
   fmt.Printf("length =%d capacity=%d sliceDetails=%v\n",len(x),cap(x),x)
}
click below button to copy the code. By - golang tutorial - team
golang , gopro , google go , golang tutorial , google language , go language , go programming language

Output for the above go programming code

length =0 capacity =0 sliceDetails =[]
slice is nil

sub-slicing

  • Slice allows lower-bound and upper bound to be specified to get the subslice of it using[lower-bound:upper-bound].

append() and copy() functions

  • Slice allows increasing the capacity of a slice using append() function.Using copy() function, contents of a source slice are copied to destination slice
package main

	import "fmt"

	func main() {
/// Unlike arrays, slices are typed only by the elements they contain (not the number of elements). To create an empty slice with non-zero length, use the builtin make. Here we make a slice of strings of length 3 (initially zero-valued).
	    s := make([]string, 3)
    fmt.Println("student:", s)
/// We can set and get just like with arrays.
	    s[0] = "a"
    s[1] = "b"
    s[2] = "c"
    fmt.Println("setValue:", s)
    fmt.Println("getValue:", s[2])
/// len returns the length of the slice as expected
.	    fmt.Println("length:", len(s))
///// In addition to these basic operations, slices support several more that make them richer than arrays. One is the builtin append, which returns a slice containing one or more new values. Note that we need to accept a return value from append as we may get a new slice value.
	    s = append(s, "d")
    s = append(s, "e", "f")
    fmt.Println("append:", s)
/// Slices can also be copy’d. Here we create an studentty slice cof the same length as s and copy into c from s.
	    c := make([]string, len(s))
    copy(c, s)
    fmt.Println("copy:", c)
// Slices support a “slice” operator with the syntaxslice[low:high]. For example, this gets a slice of the elements s[2], s[3], and s[4].
	    l := s[2:5]
    fmt.Println("slice 1:", l)
// This slices up to (but excluding) s[5].
	    l = s[:5]
    fmt.Println("slice 2:", l)
// And this slices up from (and including) s[2].
	    l = s[2:]
    fmt.Println("slice 3:", l)
// We can declare and initialize a variable for slice in a single line as well.
	    t := []string{"g", "h", "i"}
    fmt.Println("dcl:", t)
// Slices can be composed into multi-dimensional data structures. The length of the inner slices can vary, unlike with multi-dimensional arrays.
	    twoD := make([][]int, 3)
    for i := 0; i < 3; i++ {
        innerLen := i + 1
        twoD[i] = make([]int, innerLen)
        for j := 0; j < innerLen; j++ {
            twoD[i][j] = i + j
        }
    }
    fmt.Println("2d: ", twoD)
}
click below button to copy the code. By - golang tutorial - team

Output for the above golang programming

$ go run slices.go
student: [  ]
setValue: [a b c]
getValue: c
length: 3
append: [a b c d e f]
copy: [a b c d e f]
slice 1: [c d e]
slice 2: [a b c d e]
slice 3: [c d e f]
dcl: [g h i]
2d:  [[0] [1 2] [2 3 4]]

Related Searches to Go slicing