How do you declare and initialize a slice in Go?
In Go, a slice is a highly flexible and powerful built-in type that provides dynamic array-like functionality. It wraps an array and offers dynamic sizing capabilities. Below are several common methods to declare and initialize slices in Go:1. Using the built-in functionThe function creates a slice with a specified type, length, and capacity. The syntax is:Here, represents the element type of the slice, is the initial length, and is the capacity. If capacity is omitted, it defaults to the same value as length.For example, creating an int slice with both length and capacity set to 5:2. Using slice literalsYou can initialize slices directly using slice literals, which function similarly to array literals but without requiring explicit length specification.For example, creating and initializing an int slice with specific elements:3. Slicing from arrays or other slicesYou can create a new slice from an existing array or slice. The syntax is:Here, can be an array or a slice, is the starting index (inclusive), and is the ending index (exclusive).For example, creating a slice from an array:ExampleWe demonstrate a simple example to illustrate how to use these methods:In this example, we demonstrate three different methods for declaring and initializing slices, along with how to print their contents. These fundamental operations are the most commonly used when working with slices.