Slices in Go
Go: Slices
Slices are an important data type in Go, it provides a convenient and efficient way of working with sequences of typed data than arrays. Slices are analogous to arrays, but have some unusual properties. In this article we will look at what slices are and how they are used in Golang.
1. Slice declaration and initialization in Go
- Using array literal
letters := []string{"a", "b", "c", "d"}
- Using
make
function
// syntax
func make([]T, len, cap) []T
// example
var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}
- Slices modification
// you can modify values like this
s[0] = "a"
s[1] = "b"
s[2] = "c"
// push values like we do in array
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("apd:", s)
2. Copy Slices in Go
Slices can also be copy’d. Here we create an empty slice c of the same length as s and copy into c from s.
c := make([]string, len(s))
copy(c, s)
fmt.Println("cpy:", c)
slice
operator
3. Slices support a “slice” operator with the syntax slice[low:high], which will return new Slices with elements from indexes low
to high-1
var s []byte
s = make([]byte, 5, 5)
l = s[:5]
fmt.Println("sl2:", l)
4. Slices as multi-dimensional data structure
Slices can be composed into multi-dimensional data structures. The length of the inner slices can vary, unlike with multi-dimensional array
twoDSlice := make([][]int, 3)
for i := 0; i < 3; i++ {
innerLen := i + 1
twoDSlice[i] = make([]int, innerLen)
for j := 0; j < innerLen; j++ {
twoDSlice[i][j] = i + j
}
}
fmt.Println("2d: ", twoDSlice)
//2d: [[0] [1 2] [2 3 4]]
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go