Mutable and Immutable Data Types in GoLang
January 14, 2022 • ☕️ 2 min read • 🏷 computer, software
Translated by author into: English
Mutable Data Types
In Golang, mutable data types are mutable and are used for data that is allowed to be changed. These data types allow data to be manipulated more dynamically and increase the flexibility of programs.
Mutable data types are a data type that can be changed without reallocating any part of the memory assigned at program startup. In simple terms, a variable is mutable if its value can be changed without reallocating itself to a new memory space.
The value in a memory address of the Mutable data type can be changed. It means that we don’t have to reallocate any memory or change the pointer of a variable to point to another address to change the value of this variable.
someNumber := 15
// The value of someNumber is 15 and is stored in a memory addresses. Example: 0x12212
someNumber = 18
// If the data type is mutable, we can directly change the value in the memory address.
// The memory address pointed to by the variable someNumber has not changed.
fmt.Println(someNumber) // 18
There are several mutable data types in Golang:
- Array
- Slice
- Map
- Channels
Immutable Data Types
In Golang, immutable data types cannot be changed and are used for data that should not be changed. These data types are used to increase the reliability and comprehensibility of the programs because they cannot be changed and therefore the way the program works is easier to understand.
An immutable data type is a data type that cannot be changed without allocating new memory. Therefore, the Immutable data type must reallocate memory to modify the value of a variable. This can be a disadvantage if the variable holds a large set of values because it would require a lot of memory reallocation for a small change in value.
Immutable data types also mean that you cannot change the value at the memory address the variable points to, but you can make a variable point to a different memory location to change its contents.
city := "Ankara"
// The value "Ankara" is stored in a memory location. Example: 0x12212
city = "New York"
// The value "New York" will be located in a different memory location, such as 0x85574.
// The memory address that the variable city points to is changed, not the value of the memory address.
There are several mutable data types in Golang.
- String
- Boolean, Int, Float
- Pointers
- Interfaces
Resources
- https://www.golang-book.com/books/intro/3
- https://www.digitalocean.com/community/tutorials/understanding-data-types-in-go