×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

What is the default value of a slice in Go language?

Here, we will learn about the slice variable and the default value of a slice in Golang.
Submitted by IncludeHelp, on October 03, 2021

A slice is a variable-length sequence that stores elements of a similar type. The default value of a slice variable in the Go programming language is nil. The length and capacity of a nil slice is 0. But if you print the nil slice – the output will be "[]".

Example 1:

// Golang program to demonstrate the
// default values of a slice

package main

import "fmt"

func main() {
	var x []int

	fmt.Println("Default value of a slice is", x)
	fmt.Println("Length of an empty slice is", len(x))
	fmt.Println("Capacity of an empty slice is", cap(x))
}

Output:

Default value of a slice is []
Length of an empty slice is 0
Capacity of an empty slice is 0

Example 2:

// Golang program to demonstrate the
// default value of slices

package main

import "fmt"

func main() {
	var x []int
	var y []float64
	var z []string

	// Printing the types & default values
	fmt.Printf("x: %T, %v\n", x, x)
	fmt.Printf("y: %T, %v\n", y, y)
	fmt.Printf("z: %T, %v\n", z, z)
}

Output:

x: []int, []
y: []float64, []
z: []string, []

Golang FAQ »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.