Here, the type int is int64 (because I'm on a 64-bit system), so each element takes up 8 bytes of memory. The addresses of the elements are spaced 8 bytes apart (0 -> 8 -> 16).
Extra:
Let the compiler determine the size:
arr := [...]int{3, 5, 6, 2, 1} // [5]int
Initialize specific indices:
The index: value syntax assigns values to selected indices. Unspecified indices remain zero-valued.
slice1 := arr[2:4] // [20 30] (elements at index 2 and 3)slice2 := arr[:4] // [0 10 20 30] (from the start to index 3)slice3 := arr[4:] // [40] (from index 4 to the end)slice4 := arr[:] // [0 10 20 30 40] (the entire array)
Slicing does not copy the elements. It creates a slice that refers to the same underlying array.
slice := make([]int, 5) // []int{0, 0, 0, 0, 0} (non-zero length but zero valued)
Slices have a length, which is the number of elements they contain, and a capacity, which is the size of the underlying array they reference. The initial capacity is automatically set to match the initial length.
If you append elements to a slice beyond its current capacity, Go automatically handles this by allocating a larger (2x) array and copying the existing elements into it at a new memory address. This can be an expensive operation in terms of performance.
To improve performance, we can predefine the capacity of a slice. Predefining the capacity helps avoid unnecessary reallocations when appending elements.
slice := make([]int, 0, 20) // the third argument specifies capacity.fmt.Println(slice) // []fmt.Println(len(slice)) // len: 0fmt.Println(cap(slice)) // cap: 20
Predefining the capacity manually only makes sense when you have a reasonable knowledge of how the data will grow or change over time.
func main() { a := make([]int, 5, 7) fmt.Println("a:", a) // a: [0 0 0 0 0] b := append(a, 1) fmt.Println("b:", b) // b: [0 0 0 0 0 1] c := append(a, 2) fmt.Println("a:", a) // a: [0 0 0 0 0] fmt.Println("b:", b) // b: [0 0 0 0 0 2] (b got updated because of c) fmt.Println("c:", c) // c: [0 0 0 0 0 2]}
Here, when creating the b slice, the a slice has a capacity of 7 and a length of 5, which means it can add a new element without allocating a new array. So, b now references the same underlying array as a. The same thing happens when creating c. It also references the same array as a. At this point, because both b and c share the same underlying array, appending 2 through c updates the 1 that was appended through b.
This unexpected behavior would not occur if there were not enough capacity for the new element. In that case, Go would allocate a new array and copy the existing elements to it, resulting in new addresses. But still, it is prone to go unexpected.
Maps in Go are unordered collections of key-value pairs.
Syntax:
map[keyType]valueType
Initialize:
m := make(map[string]int)
or
m := map[string]int{}
or with values:
m := map[string]int{ "one": 1, "two": 2, "three": 3,}
You cannot just declare a map with var m map[string]int and then assign values to it. If you try, you will get a panic: assignment to entry in nil map. That is why you need to initialize the map first, either empty or with values as shown above before using it.
Struct tags are metadata attached to struct fields. They are typically used by packages like encoding/json to control how fields are encoded or decoded.
By default, Go uses struct field names as they are when encoding to JSON or other formats. Suppose you need to export the fields, which requires the field names to be capitalized. This often results in capitalized field names in the JSON output, which may not match your desired JSON structure or naming convention. Struct tags allow you to specify how the fields should be named in other formats.
type User struct { Id int `json:"id"` Name string `json:"name"` Email string `json:"email"`}func main() { myUser := User{ Id: 1, Name: "John", Email: "hello@example.com", } fmt.Printf("myUser: %+v\n", myUser) // myUser: {Id:1 Name:John Email:hello@example.com} jUser, _ := json.Marshal(myUser) // Converting struct to JSON fmt.Printf("jUser: %+v\n", string(jUser)) // jUser: {"id":1,"name":"John","email":"hello@example.com"}}
Tags use backticks and the format: key:"value", and are not limited to json.