Created
October 28, 2015 08:56
-
-
Save tucnak/37240ebff4c64841570e to your computer and use it in GitHub Desktop.
Meet the Slice!
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
// Some numbers, please! | |
numbers := []int{1, 2, 3, 4, 5} | |
log(numbers) // 1. [1 2 3 4 5] | |
log(numbers[2:]) // 2. [3 4 5] | |
log(numbers[1:3]) // 3. [2 3] | |
// Fun fact: you can’t use negative indices! | |
// | |
// numbers[:-1] from Python won’t work. Instead, | |
// you are supposed to do this: | |
// | |
log(numbers[:len(numbers)-1]) // 4. [1 2 3 4] | |
// “Terrific” readability, Mr. Pike! Well done! | |
// | |
// Now let’s say, I want to append six: | |
// | |
numbers = append(numbers, 6) | |
log(numbers) // 5. [1 2 3 4 5 6] | |
// Remove number 3 from numbers: | |
// | |
numbers = append(numbers[:2], numbers[3:]...) | |
log(numbers) // 6. [1 2 4 5 6] | |
// Wanna insert some number? Don’t worry, there is | |
// a *common* best practice in Go! | |
// | |
// I particularly love the ... thing, haha. | |
// | |
numbers = append(numbers[:2], append([]int{3}, numbers[2:]...)...) | |
log(numbers) // 7. [1 2 3 4 5 6] | |
// In order to copy a slice, here is what you do: | |
// | |
copiedNumbers := make([]int, len(numbers)) | |
copy(copiedNumbers, numbers) | |
log(copiedNumbers) // 8. [1 2 3 4 5 6] | |
// And there’s more. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment