乐闻世界logo
搜索文章和话题

How do you declare and initialize a slice in Go?

1个答案

1

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 make function

The make function creates a slice with a specified type, length, and capacity. The syntax is:

go
s := make([]type, length, capacity)

Here, type represents the element type of the slice, length is the initial length, and capacity 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:

go
s := make([]int, 5, 5)

2. Using slice literals

You can initialize slices directly using slice literals, which function similarly to array literals but without requiring explicit length specification.

go
s := []type{value1, value2, value3, ...}

For example, creating and initializing an int slice with specific elements:

go
s := []int{1, 2, 3, 4, 5}

3. Slicing from arrays or other slices

You can create a new slice from an existing array or slice. The syntax is:

go
s := arr[startIndex:endIndex]

Here, arr can be an array or a slice, startIndex is the starting index (inclusive), and endIndex is the ending index (exclusive).

For example, creating a slice from an array:

go
arr := [5]int{1, 2, 3, 4, 5} s := arr[1:4] // s contains elements 2, 3, 4

Example

We demonstrate a simple example to illustrate how to use these methods:

go
package main import "fmt" func main() { // Using make function a := make([]int, 3) // length and capacity are both 3 fmt.Println("Slice a:", a) // Using slice literals b := []int{1, 2, 3, 4, 5} fmt.Println("Slice b:", b) // Slicing from array arr := [5]int{1, 2, 3, 4, 5} c := arr[1:4] // includes elements from index 1 to 3 fmt.Println("Slice c:", c) }

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.

2024年8月7日 21:49 回复

你的答案