Q:

Golang program to demonstrate the different ways to create slices

belongs to collection: Golang Slices Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to create a new slice from the exis... >>
<< Golang program to find the capacity of a slice...