Thursday 2 May 2019

Go language: Get slice from a slice


You can create a slice from a slice using the notation '[startPositon:endPosition]'.

Example
subSlice := mySlice[startPosition:endPositon]

Above statement creates a slice from ‘mySlice’. Elements start from startPosition (inclusive), and end at endPoistion (exclusive).

App.go
package main

import (
 "fmt"
)

func main() {
 slice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

 subSlice := slice[3:6]

 fmt.Println("slice : ", slice)
 fmt.Println("subSlice : ", subSlice)
}

Output
slice :  [0 1 2 3 4 5 6 7 8 9]
subSlice :  [3 4 5]



Previous                                                 Next                                                 Home

No comments:

Post a Comment