Back to: Golang
Slices are a dynamic and flexible data structure that allows you to create and manipulate a sequence of elements of the same type. Unlike arrays, slices can grow or shrink in size during runtime, making them a more versatile data structure for handling collections of data.
Here is an example of how to declare and initialize a slice in Golang:
package main
import "fmt"
func main() {
slice := []int{1, 2, 3, 4, 5} // Declare and initialize a slice of integers
fmt.Println(slice) // Print the slice to the console
}
In this example, we declare and initialize a slice called slice
that contains five integers. The size of the slice is not specified in the declaration, as slices are dynamic data structures that can grow or shrink as needed.
You can also create an empty slice by using the make
function, like this:
package main
import "fmt"
func main() {
slice := make([]int, 5) // Create an empty slice of 5 integers
fmt.Println(slice) // Print the slice to the console
}
In this example, we create an empty slice called slice
of length 5 using the make
function. The make
function takes two arguments: the type of the slice and the length of the slice.
You can add new elements to a slice using the append
function, like this:
package main
import "fmt"
func main() {
slice := []int{1, 2, 3} // Declare and initialize a slice of integers
slice = append(slice, 4, 5) // Add two new elements to the slice
fmt.Println(slice) // Print the updated slice to the console
}
In this example, we declare and initialize a slice called slice
with three integers. We then use the append
function to add two new elements to the slice: the integers 4 and 5. Finally, we print the updated slice to the console.
You can also access and modify elements in a slice using their indices, just like with arrays. Here’s an example:
package main
import "fmt"
func main() {
slice := []int{1, 2, 3, 4, 5} // Declare and initialize a slice of integers
slice[2] = 10 // Modify the third element of the slice
fmt.Println(slice) // Print the updated slice to the console
}
In this example, we access the third element of the slice
slice using its index (which is 2, since slices are zero-indexed) and modify its value to 10. We then print the updated slice to the console.
Follow us on social media
Follow Author