ADVERTISEMENT
ADVERTISEMENT

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

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



ADVERTISEMENT


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.