Working with Slices in Go(golang)

In other programming languages like JavaScript, slices are a function that we call that returns a shallow copy of a portion of an array into a new array. In Go, they do very much the same thing, but the syntax is a bit different. It looks just like an array but with some key differences. First off, unlike arrays that are a fixed length, a slice’s length is dynamic so to declare a slice we just leave the area within square brackets empty. We could either initiate it with some elements or use an already existing array to extract certain elements to work with.
//Initiaing the slice to have the integers 1 ,2 3 in it.
mySlice := [ ]int{1, 2, 3}
One important thing to point out is that when you are assigning different variables to a slice, any changes made to that new variable will also be made to the slice as it is not a copy of the slice, but it is pointing to the actual slice itself.
The real power of a slice comes with it’s ability to grab different elements from within an array. How we get these elements is by referencing the array, and just like how we would access a certain element in an array(ex: array[0] to get first element in array) we do the same thing but with a colon. To the left of the colon will be the index in which we want to start, and to the right of the colon will grab the elements up to that index. Check out the example below of how we’re grabbing certain elements from an array.
Important to note: Changing the elements of a slice modifies the corresponding elements of its underlying array. So you do need to be careful on changing elements in a slice or you may get some unwanted side-effects.
Because slices are dynamic in length, we are able to add and remove elements. If you’re coming from another programming language you may know of keywords like pop, shift, push, and unshift. Go does not use these keywords, so how we would go about applying the same functionality goes as follows:
With slices we have a lot more power at our fingertips than we do with arrays as they’re a lot more unrestrictive, thus having more practical uses. Hope these examples helped! As always, Happy Coding!