Go (or Golang) is a modern, statically typed, compiled programming language designed for building scalable, concurrent and efficient software. It provides a variety of built-in functions and features to help developers write concise and efficient code. These include the new() and make() functions, which may appear similar at first glance, but are used for different purposes in Go and are critical for memory allocation and data initialization.
new() and make() functions
new()
andmake()
They are all built-in functions in Go, used to allocate memory. However, they are used in different data types and scenarios:
new() function:
-
new()
Used to allocate memory for value types (such as integers, floating point numbers, structures) and return a pointer to the newly allocated zero value. - It accepts an argument, namely the type, and returns a pointer to that type.
Make() function:
-
make()
Used to create and initialize slices, maps, and channels, which are reference types in Go. - It accepts two or three parameters depending on the type and returns an initialized (non-zero value) value that can be used immediately.
Understand the new() function
new()
The syntax of the function is very simple, as shown below:
func new(Type) *Type
HereType
The type of value for which we want to allocate memory. Let's see how to use onenew()
Example.
In this example, we usenew()
CreatedPerson
A new instance of the structure, and then use a pointer to assign the value to its fields.
package main import "fmt" type Person struct { Name string Age int } func main() { // Using new() to allocate memory for a Person struct p := new(Person) ("%T\n", p) // Accessing struct fields using the pointer = "Alice" = 30 // Displaying the values ("Name:", ) ("Age:", ) }
This program will produce the output shown below.
> go run * Name: Alice Age: 30
Understand the make() function
make()
The syntax of a function depends on the type it is used for.
For slices (Slices)
func make([]Type, len, cap) []Type
-
Type
: The type of element that the slice will save. -
len
: The initial length of the slice. -
cap
: The capacity of the slice, which is optional and is used to specify the capacity of the underlying array. If not provided, it defaults to the same length as the one.
usemake()
Example of creating slices:
package main import "fmt" func main() { // Using make() to create a slice of integers numbers := make([]int, 5, 10) // Displaying the slice's length, capacity, and values ("Length:", len(numbers)) ("Capacity:", cap(numbers)) ("Values:", numbers) // Using make() to create a slice of integers numbersWithoutOptional := make([]int, 5) // Displaying the slice's length, capacity, and values ("Length:", len(numbersWithoutOptional)) ("Capacity:", cap(numbersWithoutOptional)) ("Values:", numbersWithoutOptional) }
This program will produce the following output.
> go run Length: 5 Capacity: 10 Values: [0 0 0 0 0] Length: 5 Capacity: 5 Values: [0 0 0 0 0]
For Maps
func make(map[KeyType]ValueType, initialCapacity int) map[KeyType]ValueType
-
KeyType
: The type of the key in the map. -
ValueType
: The type of value associated with the key. -
initialCapacity
: The initial capacity of the map. This is optional, but can be used to optimize performance when the number of elements is known in advance.
usemake()
Example of creating a map:
package main import "fmt" func main() { // Using make() to create a map of string keys and int values scores := make(map[string]int) // Adding values to the map scores["Alice"] = 95 scores["Bob"] = 87 // Displaying the map ("Scores:", scores) } > go run Scores: map[Alice:95 Bob:87]
For Channels
func make(chan Type, capacity int) chan Type
-
Type
: The type of value that can be sent and received through the channel. -
capacity
: The buffer size of the channel. If set to 0, the channel is unbuffered.
usemake()
Example of creating a channel:
package main import ( "fmt" "time" ) func main() { // Using make() to create an unbuffered channel of integers ch := make(chan int) // Sending data into the channel using a goroutine go func() { for i := 1; i <= 5; i++ { ch <- i () // Simulating some work before sending the next value } close(ch) }() // Receiving data from the channel for num := range ch { ("Received:", num) } } > go run Received: 1 Received: 2 Received: 3 Received: 4 Received: 5
in conclusion
In this blog post, we unravel thenew()
andmake()
Mysteries of functions and explain their differences and uses. To summarize:
- Use new() to allocate memory for the value type and get a pointer to a zero value.
- Use make() to create and initialize slices, maps, and channels (reference types) and specify their types and initial capacity.
Understanding the difference between new() and make() is critical to efficient memory allocation and data initialization in Go. Using these functions correctly will produce cleaner and more optimized code in your Golang project.
The above is a detailed article that will reveal the differences and uses of new() and make() functions in Go. For more information about Go new() and make() functions, please follow my other related articles!