What is Slice in Golang?
Slices in Go are a flexible and efficient way to represent arrays, and slices are often used instead of arrays because of their dynamic size and additional features. Here's what you need to know about Slices in Golang .
A slice is a reference to a portion of an array. It is a data structure that describes a portion of an array by specifying the starting index and length of that portion. This allows you to work with a portion of an array as if it were a separate array. In Go, slices are more powerful, flexible, and convenient than arrays and are lightweight data structures. Slices are variable-length sequences that store elements of the same type; you are not allowed to store elements of different types in the same slice.
It is like an array with index values and length, but the size of slices is variable, they do not have a fixed size like an array. Internally, slices and arrays are connected, a slice is a reference to an underlying array. It is allowed to store duplicate elements in the slice.
Vị trí chỉ mục đầu tiên trong một slice của Golang luôn là 0 và vị trí chỉ mục cuối cùng sẽ là (chiều dài của slice- 1).
Let's consider the example below to understand how to create slices in Golang
package main import "fmt" func main() { array := [5]int{1, 2, 3, 4, 5} slice := array[1:4] fmt.Println("Array: ", array) fmt.Println("Slice: ", slice) }
Result:
Array: [1 2 3 4 5] Slice: [2 3 4]
In this example, the array is created with 5 elements and the slice is created by specifying the starting index as 1 and length as 4. The slice now contains elements 2, 3 and 4 from the original array.
The slices are dynamic, meaning their size can change over time.
Slice: [1 2 3 4 5 6]
When you add or remove elements, Go provides several built-in functions that allow you to modify slices, such as add, copy, and remove.
Example of how to add elements to a slice in Golang:
package main import "fmt" func main() { slice := []int{1, 2, 3} slice = append(slice, 4, 5, 6) fmt.Println("Slice: ", slice) }
Result:
Slice: [1 2 3 4 5 6]
In this example, the append function is used to add elements 4, 5, 6 to the slice. The result is a new slice containing elements 1, 2, 3, 4, 5, 6.
Slices in Go are a powerful and flexible data structure that can be used to represent arrays. They provide a more dynamic and efficient way of working with arrays and are widely used in Go programs.
Declare Slice
A slice is declared like an array, but it does not contain the size of the slice. So it can grow or shrink as required.
Syntax:
[]T or []T{} or []T{value1, value2, value3, .value n}
Here, T is the element type. For example:
var my_slice[]int
Components of Slice
A slice contains three components:
- Pointer: Pointer is used to point to the first element of the array accessible through the slice. Here, the pointed element need not be the first element of the array.
- Length : Length is the total number of elements in the array.
- Capacity: Capacity represents the maximum size to which it can expand.
Let us discuss all these components with the help of an example:
For example:
//Chương trình Golang minh họa // hoạt động của các thành phần slice package main import "fmt" func main() { // Tạo một mảng arr := [7]string{"This", "is", "the", "tutorial", "of", "Go", "language"} // Hiện mảng fmt.Println("Array:", arr) // Tạo một slice myslice := arr[1:6] // Hiện slice fmt.Println("Slice:", myslice) // Hiện chiều dài của slice fmt.Printf("Length of the slice: %d", len(myslice)) // Hiển thị dung lượng của slice fmt.Printf("nCapacity of the slice: %d", cap(myslice)) }
Result:
Array: [This is the tutorial of Go language] Slice: [is the tutorial of Go] Length of the slice: 5 Capacity of the slice: 6
In the above example, we create a slice from the given array. Here the slice pointer points to index 1 since the lower bound of the slice is set to one so it starts accessing the elements from index 1. The length of the slice is 5 which means the total number of elements present in the slice is 5 and the capacity of the slice is 6 which means it can store a maximum of 6 elements in it.
How to create and initialize a Slice?
In Go language, a slice can be created and initialized in the following ways:
Using slice literal: You can create a slice using slice literal. Creating a slice literal is similar to creating an array literal, but with one difference: you are not allowed to specify the size of the slice within the square brackets [] . As shown in the example below, the right-hand side of this expression is a slice literal .
var my_slice_1 = []string{"Geeks", "for", "Geeks"}
Note: Always remember that when you create a slice using a string, it first creates an array and then returns a slice reference to that array.
For example:
// Chương trình Go minh họa cách // tạo một slice bằng một slice // literal package main import "fmt" func main() { // Tạo một slice // bằng key var var my_slice_1 = []string{"Geeks", "for", "Geeks"} fmt.Println("My Slice 1:", my_slice_1) // Tạo một slice //bằng khai báo viết tắt my_slice_2 := []int{12, 45, 67, 56, 43, 34, 45} fmt.Println("My Slice 2:", my_slice_2) }
Result:
My Slice 1: [Geeks for Geeks] My Slice 2: [12 45 67 56 43 34 45]
Use an array
As we know, slice is a reference of array so you can create a slice from given array. To create a slice from given array, you need to specify lower and upper bound first, that is slice can take elements from array starting from lower bound to upper bound. It does not include elements above from upper bound. As shown in the example below:
Syntax:
array_name[low:high]
This syntax will return a new slice.
Note: The default value of the lower bound is 0 and the default value of the upper bound is the total number of elements present in the given array.
For example:
// Chương trình Go minh họa cách // tạo slice từ mảng package main import "fmt" func main() { // Tạo một mảng arr := [4]string{"Geeks", "for", "Geeks", "GFG"} // Tạo slice từ mảng được cung cấp var my_slice_1 = arr[1:2] my_slice_2 := arr[0:] my_slice_3 := arr[:2] my_slice_4 := arr[:] // Hiện kết quả fmt.Println("My Array: ", arr) fmt.Println("My Slice 1: ", my_slice_1) fmt.Println("My Slice 2: ", my_slice_2) fmt.Println("My Slice 3: ", my_slice_3) fmt.Println("My Slice 4: ", my_slice_4) }
Result:
My Array: [Geeks for Geeks GFG] My Slice 1: [for] My Slice 2: [Geeks for Geeks GFG] My Slice 3: [Geeks for] My Slice 4: [Geeks for Geeks GFG]
You should read it
- What is GoLang? How to install GoLang on Windows 10
- Difference between Go and C++
- What is Golang? Things you need to know about Golang programming language
- Structural equality in Golang
- What is Golang? Why should you use Golang language?
- Arrays in Golang
- Functions are fields in Golang
- Anonymous structures and fields in Golang
May be interested
- Anonymous structures and fields in Golanganonymous structs in golang are temporary structures with no names used for one-time purposes, while anonymous fields allow embedding of unnamed fields.
- Recommended fields in Golangin go structs, fields are encouraged to be the same as anonymous fields, the type of the field is the name of the field.
- How to pass an array to a function in Golangto manage this data efficiently, you often need to pass arrays to functions. in this article, we will learn how to pass arrays to functions in golang.
- What is the difference between Go and Java?is golang better than java? is golang harder than java? can golang replace java? this comparison will give you the answer.
- How to create basic program in Golanghello, world! is the first basic program in any programming language. you can write this first program in golang by following the steps below.
- How to Install Go on Windowsgolang can be easily installed on windows. here is a step-by-step guide to install golang on windows.
- Recommended methods in Golangin golang structure, recommended methods work the same way as recommended fields.
- How to implement a graph data structure in Golangcharts are one of the essential data structures that you must know as a programmer. let's learn how to create graph/graph data structures in golang !
- Difference between Go and Pythontwo popular programming language choices today are go and python. in this article, let's explore the differences between golang & python.
- Malware that specializes in eavesdropping and sabotage is discovered hiding on Telegramnew golang malware is using telegram as a 'lever' to spread itself everywhere.