search

Explain the use of Go's composite literals for initializing composite data types?

In Go, composite literals are a concise way of initializing composite data types such as arrays, slices, maps, and structs. They allow us to define and initialize composite values in a single expression.

The syntax for composite literals is as follows:

type value = Type{ Elements }

Here, **Type** is the type of the composite value, and **Elements** are the elements of the composite value. The type and elements are enclosed in curly braces **{ }**, and the elements are separated by commas.

For example, to initialize an array of integers with the values 1, 2, and 3, we can use the following composite literal:

a := [3]int{1, 2, 3}

Similarly, to initialize a slice of integers with the same values, we can use the following composite literal:

s := []int{1, 2, 3}

To initialize a map with string keys and integer values, we can use the following composite literal:

m := map[string]int{"one": 1, "two": 2, "three": 3}

And to initialize a struct with string and integer fields, we can use the following composite literal:

p := struct {
    name string
    age  int
}{
    name: "Alice",
    age:  30,
}

Composite literals can also be used to initialize nested composite data types. For example, to initialize a slice of structs with string and integer fields, we can use the following composite literal:

people := []struct {
    name string
    age  int
}{
    {"Alice", 30},
    {"Bob", 40},
    {"Charlie", 50},
}

In summary, composite literals are a concise way of initializing composite data types in Go. They allow us to define and initialize composite values in a single expression, and can be used for arrays, slices, maps, and structs, as well as nested composite data types.

Related Questions You Might Be Interested