100 Mistakes in Golang: Chapter 3

17 Creating confusion with octal literals In Go, an integer literal starting with 0 is considered an octal integer (base 8). Note the integer literal representations in Golang: Binary - Uses a 0b or 0B prefix (for example, 0b100 is equal to 4 in base 10) Octal - Uses a 0 or 0o prefix (for example, 0o10 is equal 8 in base 10) Hexadecimal - Uses an 0x or 0X prefix (for example, 0xF is equal to 15 in base 10) Imaginary - Uses an i suffix (for example, 3i) 20 Not understanding slice length and capacity In Go, a slice is backed by an array. That means the slice’s data is stored contiguously in an array data structure. A slice also handles the logic of adding an element if the backing array is full or shrinking the backing array if it’s almost empty. ...

February 20, 2025 · Last updated on April 5, 2025 · 12 min · KKKZOZ

100 Mistakes in Golang: Chapter 4

30: Ignoring the fact that elements are copied in range loops type account struct { balance float32 } accounts := []account{ {balance: 100.}, {balance: 200.}, {balance: 300.}, } for _, a := range accounts { a.balance += 1000 } // Output: [{100} {200} {300}] In this example, the range loop does not affect the slice’s content. In Go, everything we assign is a copy: If we assign the result of a function returning a struct, it performs a copy of that struct. If we assign the result of a function returning a pointer, it performs a copy of the memory address (an address is 64 bits long on a 64-bit architecture). Solutions: ...

February 20, 2025 · Last updated on April 5, 2025 · 3 min · KKKZOZ