Skip to content

Instantly share code, notes, and snippets.

@cjgiridhar
Created January 27, 2019 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjgiridhar/e76ed67b14fc616adc112bd6e832846b to your computer and use it in GitHub Desktop.
Save cjgiridhar/e76ed67b14fc616adc112bd6e832846b to your computer and use it in GitHub Desktop.
Passing slices to functions
package main
import (
"fmt"
)
/* Function that doubles every element in the slice */
func workonslice(slice []int) {
for i := range slice {
slice[i] *= 2
}
}
func main() {
/* Create slice from array of integers */
numbers := [...]int{1, 2, 3, 4, 5}
slice := numbers[1:4]
/* Returns: Elements in slice are: [2 3 4] */
fmt.Println("Elements in slice are:", slice)
/* Get 1st element in slice through indices */
/* Returns: First elements in slice: 2 */
fmt.Println("First elements in slice:", slice[0])
/* Function call on slice */
workonslice(slice)
/* Returns: Elements in slice post function call: [4 6 8] */
fmt.Println("Elements in slice post function call:", slice)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment