Golang program to demonstrate the different ways to create slices

Here, we are going to demonstrate the different ways to create slices in Golang (Go Language)?
Submitted by Nidhi, on March 15, 2021 [Last updated : March 04, 2023]

Different ways to create slices in Golang

Problem Solution:

In this program, we will use different ways to create slices from a string array and print them on the console screen.

Program/Source Code:

The source code to demonstrate the different ways to create slices is given below. The given program is compiled and executed successfully.

Golang code to create slices using different ways

// Golang program to demonstrate
// the different ways to create slices

package main

import "fmt"

func main() {
	//Create an array of strings.
	arr := []string{"Hello ", "How ", "are ", "you"}

	//different ways to create slices.
	Slice1 := arr[1:3]
	Slice2 := arr[1:]
	Slice3 := arr[:3]
	Slice4 := arr[:]

	fmt.Println("slice1: ", Slice1)
	fmt.Println("slice2: ", Slice2)
	fmt.Println("slice3: ", Slice3)
	fmt.Println("slice4: ", Slice4)
}

Output:

slice1:  [How  are ]
slice2:  [How  are  you]
slice3:  [Hello  How  are ]
slice4:  [Hello  How  are  you]

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In the main() function, we created an array of strings. Then we used different ways to create slices from the array of strings. After that print all slices on the console screen.

Golang Slices Programs »





Comments and Discussions!

Load comments ↻





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