navigation

Complex String Slice in Golang

There are two terms: Slice and Composite Literal. Slice is a composite data type similar to an array that is used to hold elements of the same data type. The main difference between an array and a slice is that a slice can change size dynamically but is not an array. Composite literals are used to construct values ​​for arrays, structures, slices, and maps. Each time they are evaluated, a new value is created. They consist of the type of the literal followed by a list of elements surrounded by curly braces.

 

In this article we will learn how to create a slice and use synthetic literals in Golang .

For example:

// Chương trình Go hiện slice // - composite literal package main import "fmt" func main() { // Slice với composite literal // Slice cho phép bạn nhóm lại // các giá trị cùng loại // kiểu giá trị ở đây là int s1 := []int{23, 56, 89, 34} // hiện giá trị fmt.Println(s1) }

Result:

[23 56 89 34]

 

Hope you understand the term composite literal correctly . Basically, assigning values ​​or initializing arrays, slices, etc. is done using composite literal values . They are often used to create a series of values ​​of similar type.

A Go composite slice literal is a shorthand syntax for creating a slice by directly specifying its elements. A composite slice literal is written as []T{e1, e2, ., ek} where T is the type of the elements in the slice and e1, e2, ., ek are the inner elements.

Here is an example illustrating how to create a composite slice literal in Go:

package main import "fmt" func main() { slice := []int{1, 2, 3, 4, 5} fmt.Println("Slice: ", slice) }

Result:

Slice: [1 2 3 4 5]

In this example, the slice constituent element []int{1, 2, 3, 4, 5} creates a slice with elements 1, 2, 3, 4, 5. The type of the elements in the slice is int, so the type of the slice is []int.

The slice component can also be used to create slices of other types, such as string, float64, or custom types. The syntax is the same, and the elements in the slice must be of the same type.

Here is an example illustrating how to create a slice element of string type in Go:

package main import "fmt" func main() { slice := []string{"apple", "banana", "cherry"} fmt.Println("Slice: ", slice) }

Result:

Slice: [apple banana cherry]

In this example, the slice composition element []string{"apple", "banana", "cherry"} creates an element with the components "apple", "banana", "cherry". The type of the elements inside it is string , so the type of the element is []string .

Slice composition elements provide a concise and convenient way to create elements in Go. They are widely used in Go programs and can make your code more readable and concise.

Update 26 May 2025