Contents
Slices in Golang
Slices
What Are Slices?
- Slices are a flexible and dynamic abstraction over arrays in Go.
- They represent a contiguous segment of an array and include a pointer, length, and capacity.
- Unlike arrays, slices are resizable.
Key Features:
- Dynamic Size: Unlike arrays, slices can grow or shrink as required.
- Reference Type: Slices point to an underlying array. Changes to the slice affect the array and vice versa.
- Homogeneous Elements: Slices can only hold elements of the same type.
- Support for Duplicates: Slices can contain duplicate elements.
Slice Components:
- Pointer: Points to the starting element of the slice.
- Length: Number of elements in the slice.
- Capacity: Maximum number of elements the slice can accommodate without reallocation.
Creating Slices:
1. From Arrays: Use slicing syntax array[low:high]
.
2. Slice Literals:
mySlice := []int{1, 2, 3}
3. Using make()
:
mySlice := make([]int, length, capacity)
4. From Existing Slices: Use slicing syntax on slices.
Array elements:
10
20
30
40
50
Examples:
1. Basic Slicing:
arr := [5]int{1, 2, 3, 4, 5}
slice := arr[1:4]
fmt.Println(slice) // Output: [2 3 4]
2: Using append()
:
slice := []int{1, 2}
slice = append(slice, 3, 4)
fmt.Println(slice) // Output: [1 2 3 4]
3. Using make()
:
slice := make([]int, 3, 5)
fmt.Println(slice) // Output: [0 0 0]
4. Iterating Over Slices:
- Using
for
loop:
for i := 0; i < len(slice); i++ {
fmt.Println(slice[i])
}
- Using
range
:
for idx, val := range slice {
fmt.Printf("Index: %d, Value: %d\n", idx, val)
}
Output:
Colors in the array:
Red
Green
Blue
Slice Composite Literal in Go
There are two important terms: Slice and Composite Literal. A slice is a composite data type similar to an array, used to store multiple elements of the same data type. The key distinction between an array and a slice is that a slice can adjust its size dynamically, whereas an array cannot.
On the other hand, Composite Literals are utilized to create values for slices, arrays, structs, and maps. Each time a composite literal is evaluated, a fresh value is created. They consist of the type of the literal followed by a brace-enclosed list of elements. After reading this explanation, you’ll likely recognize composite literals and be surprised to find that you already understand them!
// Go program to demonstrate a slice
// using a composite literal
package main
import "fmt"
func main() {
// Creating a slice with a composite literal
// A slice groups together values of the same type
// Here, the values are of type float64
nums := []float64{3.14, 2.71, 1.41, 0.577}
// Displaying the slice values
fmt.Println(nums)
}
Output:
[3.14 2.71 1.41 0.577]
Slices created using composite literals are a shorthand way to initialize or assign values to slices, arrays, etc. These literals are especially handy for grouping values of similar types.
A slice composite literal in Go provides a concise syntax for creating slices by explicitly listing their elements. The syntax looks like []T{e1, e2, …, ek}
, where T
is the element type, and e1, e2, …, ek
are the slice elements.
Let’s see another example of a slice composite literal in Go:
package main
import "fmt"
func main() {
// Initializing a slice with integers
numbers := []int{10, 20, 30, 40, 50}
// Printing the slice
fmt.Println("Numbers slice:", numbers)
}
Output:
Numbers slice: [10 20 30 40 50]
In this case, the composite literal []int{10, 20, 30, 40, 50}
creates a slice containing the integers 10, 20, 30, 40, and 50. Since the element type is int
, the slice type becomes []int
.
You can also use slice composite literals for other data types like strings, float64, or even custom types. The syntax remains consistent, and the elements within the slice must share the same type.
Here’s an example of a slice composite literal with string elements:
package main
import "fmt"
func main() {
// Creating a slice of strings
fruits := []string{"mango", "grape", "peach"}
// Displaying the string slice
fmt.Println("Fruits slice:", fruits)
}
Output:
Fruits slice: [mango grape peach]
Related Chapters
- Introduction of Go-Lang
- Fundamentals in Go
- Control Statement in Go
- Functions & Methods in Go
- Structures in Go
- Arrays in Go
- Slices in Go
- File Handling in I/O
- Pointers in Go
- Concurrency in Go
- Object Oriented Programming in Go
- Defer and Error Handling in Go
- First Class Functions in Go
- Reflection in Go
- File Handling in Go