How To Create An Empty Slice In Go Lang ? | Go Lang Examples



How To Create An Empty Slice In Go Lang ? | Go Lang Examples


 Hi Guys,

Welcome to Java Inspires..

In this post, we will see how to create an empty slice in go and how to add items to this empty slice.

 sample.go

package main

import "fmt"

func main() {

	// create empty slices
	var intSlice []int    // this is int slice
	var strSlice []string // this is string slice

	// print these slices
	fmt.Println("intSlice :", intSlice)
	fmt.Println("strSlice :", strSlice)

	// print length of these slices
	fmt.Println("Length of intSlice :", len(intSlice))
	fmt.Println("Length of strSlice :", len(strSlice))

	// print capacity of these slices
	fmt.Println("Capacity of intSlice :", cap(intSlice))
	fmt.Println("Capacity of strSlice :", cap(strSlice))

	// add new elements to these slices
	intSlice = append(intSlice, 1, 2, 3, 4, 5) // can add any number of elements
	strSlice = append(strSlice, "Hello", "World", "java", "Inspires", "Go Lang")

	// print these slices
	fmt.Println("intSlice :", intSlice)
	fmt.Println("strSlice :", strSlice)

	// print length of these slices
	fmt.Println("Length of intSlice :", len(intSlice))
	fmt.Println("Length of strSlice :", len(strSlice))

	// print capacity of these slices
	fmt.Println("Capacity of intSlice :", cap(intSlice))
	fmt.Println("Capacity of strSlice :", cap(strSlice))

}

Output :

PS C:\Users\developer\Desktop> go run .\sample.go
intSlice : []
strSlice : []
Length of intSlice : 0
Length of strSlice : 0
Capacity of intSlice : 0
Capacity of strSlice : 0
intSlice : [1 2 3 4 5]
strSlice : [Hello World java Inspires Go Lang]
Length of intSlice : 5
Length of strSlice : 5
Capacity of intSlice : 6
Capacity of strSlice : 5
PS C:\Users\developer\Desktop> 

THANK YOU

Key Words : How To Create An Empty Slice In Go Lang ?, Go Language, Go Lang Examples, Java Inspires, Slices In Go Lang


Post a Comment

Previous Post Next Post