6,564 viewsAsked at 36 companies
What are slices in Go and how are they structured?
Asked at
CRTEXDigital SpiritEvroneHyperRusLamoda Tech
OZON
Positive TechnologiesRubytechSmallStartribe
VK Cloud
Wildberries
YadroАлабугаАстрал-Софт
Бюро 1440
Газпром
ИннотехКадровое агентство BWGКиберпротект
Лига Цифровой ЭкономикиМагнит ТехМагнус ТехМаском
МВидео
МТС
МТС DigitalООО Левел Тревел
СамокатСамокат Тех
СБЕР
Т-БанктехвилТехнократияЦифровая ЭволюцияЭрливидео
AI answer
A slice in Go is a dynamic, resizable sequence type that represents a reference to an array. It contains three main components: a pointer to the first element of the array, the length (number of elements in the slice), and the capacity (the maximum number of elements the slice can hold without reallocating).
Slices are convenient because they allow working with sequences of data without needing to specify a fixed size in advance, as with arrays. When adding elements using the append function, a slice can automatically expand, creating a new array if necessary.
Example of using a slice:
package main
import "fmt"
func main() {
s := []int{1, 2, 3} // creating a slice
fmt.Println(s) // [1 2 3]
s = append(s, 4, 5) // adding elements
fmt.Println(s) // [1 2 3 4 5]
}
Thus, slices are a convenient and efficient way to work with sequences in Go, combining flexibility and performance.