Created
January 27, 2019 08:46
-
-
Save cjgiridhar/e76ed67b14fc616adc112bd6e832846b to your computer and use it in GitHub Desktop.
Passing slices to functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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