#JavaInspires
Hi Guys,
Welcome to Java Inspires.
In this post, we will see how to create a Slice in go lang using make function and also how to add elements to the slice.
sample.go
package main import "fmt" func main() { //create a string type slice var strSlice = make([]string, 5) // here length and capacity is 5 //print strSlice fmt.Println("strSlice :", strSlice) // print length of slice fmt.Println("Length of strSlice :", len(strSlice)) //print capacity of strslice fmt.Println("Capacity od strSlice :", cap(strSlice)) // lets create a slice with different length and different capacity var strSl = make([]string, 5, 8) // here 5 is length and 8 is capacity // print capacity and length fmt.Println("Length of strS1 :", len(strSl)) fmt.Println("Capacity of strS1 :", cap(strSl)) // now add element to the slice strSl[0] = "Hello" strSl[1] = "Java" strSl[2] = "Inspires" //print the slice fmt.Println(strSl) }
Output :
PS C:\Users\developer\Desktop> go run .\sample.go strSlice : [ ] Length of strSlice : 5 Capacity od strSlice : 5 Length of strS1 : 5 Capacity of strS1 : 8 [Hello Java Inspires ] PS C:\Users\developer\Desktop>
THANK YOU