• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer

GitopsCentral

  • Home
  • Courses
  • Roadmap
  • About
  • Log In
  • Sign Up

Composite types: Slice

April 4, 2019 by shaik zillani

Slices

A Slice is like a dynamically-sized array. A slice type is written []T,where elements has type T. So it’s like an array without size defined.

A Slice is a light weight data structure that gives access to sequence of elements of an array, also known as slice’s underlying array.

Syntax

a[i:j]– Slice with range from i to j
a[i:]– Slice with range from i to end of the underlying array
a[:j]– Slice with range from start of the underlying array to j
a[:]– Slice, whose range is the whole array

Example

Consider the example below, arr is an array of size 5 and arr[1:4]slices it from index 1 to 3So it excludes the last one.

package main

import "fmt"

func main() {
  arr := [4]int{1, 2, 3, 4} 
  var s1 []int = arr[0:2]
  var s2 []int = arr[1:3]
  fmt.Println(s1)
  fmt.Println(s2)
}

Result

[1 2]
[2 3]

If we represent this in a mathematical fashion, slice operator is s[i:j] where 0<=i<=j<=cap(s)

Length and Capacity

Length: Length is the number of slice elements
Capacity: Capacity is the number of elements between start of slice and the end of underlying array.

The Length and capacity of a slice is defined by the function len() and cap()For the Same example above, let’s execute below,

package main
import "fmt"
func main(){
  arr := [6]int {1,2,3,4,5,6}
  var s1 []int  = arr[3:4]

  fmt.Println(s1)
  fmt.Println(len(s1),cap(s1))
}

Result

[4]
1 3

Note: A slice does not store any data, it only describes a section of an underlying array. Changing the elements of a slice will modify the corresponding elements of its underlying array

Consider the below declaration, by no defining the size of the array, the compiler will recognize this as a slice and will create the underlying array first and then creates slice pointing it

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

 

golang go,  golang

Primary Sidebar

en English
ar Arabiczh-CN Chinese (Simplified)nl Dutchen Englishfr Frenchde Germanhi Hindiid Indonesianit Italianja Japanesems Malaypt Portugueseru Russianes Spanishte Telugu

Course Tags

concurrency free go golang

Recent Posts

  • Roadmap to Mastery
  • Increase SSH connection timeout
  • Check Certificate expiry in Kubernetes
  • space invaders in golang
  • creating kubernetes cluster using eksctl
  • Facebook
  • GitHub
  • YouTube

Contact

Navigation

  • goacademy pro

Footer

  • Facebook
  • GitHub
  • Instagram
  • LinkedIn
  • Twitter

info@gitopscentral.com


+91 8341443220

© Copyright 2016-2024 gitopscentral · All Rights Reserved ·