Skip to content

Instantly share code, notes, and snippets.

@LispyAriaro
Last active November 29, 2017 13:22
Show Gist options
  • Save LispyAriaro/0d9abf8be16d942dd288a3214f51317f to your computer and use it in GitHub Desktop.
Save LispyAriaro/0d9abf8be16d942dd288a3214f51317f to your computer and use it in GitHub Desktop.
Helpful tips on using Go lang arrays and slices
- Once an array is declared, neither the type of data being stored nor its length can be changed.
- You can have an array of pointers.
```
array := [5]*int{0: new(int), 1: new(int)}
// Assign values to index 0 and 1.
*array[0] = 10
*array[1] = 20
```
-
// Declare a string array of five elements.
```
var array1 [5]string
// Declare a second string array of five elements.
// Initialize the array with colors.
array2 := [5]string{"Red", "Blue", "Green", "Yellow", "Pink"}
// Copy the values from array2 into array1.
array1 = array2
```
- Copying an array of pointers copies the pointer values and not the values that the pointers are pointing to.
- When you pass variables between functions, they’re always passed by value.
- pass variables by reference when you need to mutate it
```
// Allocate an array of 8 megabytes.
var array [1e6]int
// Pass the address of the array to the function foo.
foo(&array)
// Function foo accepts a pointer to an array of one million integers.
func foo(array *[1e6]int) {
...
}
```
- A slice can only access indexes up to its length.
Trying to access an element outside of its length will cause a runtime exception.
The elements associated with a slice’s capacity are only available for growth.
- On a 64-bit architecture, a slice requires 24 bytes of memory.
The pointer field requires 8 bytes, and the length and capacity fields require 8 bytes respectively.
Since the data associated with a slice is contained in the underlying array, there are no prob-
lems passing a copy of a slice to any function.
Only the slice is being copied, not the underlying array
- It’s important to know that range is making a copy of the value, not returning a refer-
ence. If you use the address of the value variable as a pointer to each element, you’ll
be making a mistake.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment