everyday

Slices - Golang

slice is key datatype in go which provides interface for various operations that can be performed on sequence like data structure. To create slice with pre-determined length we can use make function. We can get and set values just like we used to do in arrays.

make is special function in Go that is used to create slices, maps and channels. make can take two argument with type & size of variable that has to be declared.

    1 package main
    2 
    3 import "fmt"
    4 
    5 func main() {
               // creating a slice of type string and length of two
    6         s:=make([] string,2)
              // setting values to string array
    7         s[1]="s"
    8         s[0]="h"
              // supports different operations such as append,copy
    9         s = append(s,"2")
   10         s = append(s,"1","2")
   11         c := make([] string,len(s))
   12         l := c[0:2]
   13         copy(c,s)
   14         fmt.Println("emp",s)
   15         fmt.Println("l",l)
   16         fmt.Println("emp",c)
   17  }

#go-intro