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