Last active
August 10, 2022 10:20
-
-
Save illia-danko/65b814dd8c42b46c046e1b1383a11659 to your computer and use it in GitHub Desktop.
Golang array(slice) operations
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" | |
// Array operations in Golang. | |
// | |
// Note: a generic `array` term is using, however all operation involve go | |
// slice, which is a reference to an underline 'real' array. | |
func main() { | |
// Push back: | |
{ | |
a := []int{1, 2, 3, 4} | |
fmt.Println(append(a, 4)) // [1 2 3 4 5] | |
} | |
// Push front: | |
{ | |
a := []int{2, 3, 4, 5} | |
fmt.Println(append([]int{1}, a...)) // [1 2 3 4 5] | |
} | |
// Insert at: | |
{ | |
index := 2 | |
a := []int{1, 2, 4, 5} | |
a = append(a[:index+1], a[index:]...) | |
a[index] = 3 | |
fmt.Println(a) // [1 2 3 4 5] | |
} | |
// Delete back: | |
{ | |
a := []int{1, 2, 3, 4, 5} | |
fmt.Println(a[:len(a)-1]) // [1 2 3 4] | |
} | |
// Delete front: | |
{ | |
a := []int{1, 2, 3, 4, 5} | |
fmt.Println(a[1:]) // [2 3 4 5] | |
} | |
// Delete at position: | |
{ | |
index := 2 | |
a := []int{1, 2, 3, 4, 5} | |
fmt.Println(append(a[:index], a[index+1:]...)) // [1 2 4 5] | |
} | |
// Take subarray: | |
{ | |
a := []int{1, 2, 3, 4, 5} | |
fmt.Println(a[1:4]) // [2 3 4] | |
} | |
// Swap elements: | |
{ | |
a := []int{1, 2, 3, 4, 5} | |
a[1], a[3] = a[3], a[1] | |
fmt.Println(a) // [1 4 3 2 5] | |
} | |
// Merge two arrays: | |
{ | |
a := []int{1, 2, 3} | |
b := []int{4, 5} | |
fmt.Println(append(a, b...)) // [1 2 3 4 5] | |
} | |
// Copy array: | |
{ | |
a := []int{1, 2, 3, 4, 5} | |
b := make([]int, len(a)) | |
copy(b, a) | |
fmt.Println(b) // [1 2 3 4 5] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment