Javatpoint Logo
Javatpoint Logo

Go Slice

In Go, slice is a dynamically-sized, segmented view of an underlying array. This segment can be the entire array or a subset of an array. We define the subset of an array by indicating the start and end index. Slices provide a dynamic window onto the underlying array.

Slice Data Type Example:

Output:

[4 6 8]

Slice is like reference to an array. Slice does not store any data. If we change the elements of an array, it will also modify the underlying array. If other slice is referencing the same underlying array, their value will also be changed.

Slice is like array reference. An example of slice is given below:

Output:

[John Jim Jack jen]
[John Jim] [Jim Jack]
[John ZZZ] [ZZZ Jack]
[John ZZZ Jack jen]

Slice Literal

Slice literal is like an array literal without any length. An example of slice without length is given below:

Output:

[{1 true} {2 false} {3 true} {4 true} {5 false} {6 true}]

Omit Lower or Upper Bonds

In slice, we can omit the lower bond or the upper bonds. Zero is the default value of the lower or the upper bond.

Output:

[8 10]
[2 4 8]
[8 10 12 14]
[2 4 8 10 12 14]

Slice Length and Capacity

A slice has length and capacity. The length is the number of stored elements and the capacity is the number of elements of the underlying array counting from the beginning of the slice.

To get the length, we use len(slice) function and to get the capacity, we use cap(slice) function.

Output:

length =7 capacity=7 [2 4 6 8 10 12 14]
length =0 capacity=7 []
length =4 capacity=7 [2 4 6 8]
length =5 capacity=5 [6 8 10 12 14]

Slice Make Function

We can also create slice with the help of make function. The make function creates a zero sized array and returns slice of the array.

Output:

slice length=10 capacity=10 [0 0 0 0 0 0 0 0 0 0]
slice1 length=0 capacity=10 []
slice2 length=5 capacity=10 [0 0 0 0 0]
slice3 length=3 capacity=8 [0 0 0]





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA