Home > Article > Backend Development > golang new usage
Golang is a fast, reliable and efficient programming language. Because of its excellent performance and maintainability, it has become a popular choice in web development, server programming, big data processing and other scenarios. In this article, we will introduce the usage of the new keyword in Golang.
In Golang, new is a keyword used to allocate memory on the heap and initialize it to zero value. If you are familiar with C/C type ideas, you can use it analogously to the combination of malloc function and calloc function.
It is very simple to use the new keyword to open a memory for data. You only need to call the new function and pass in the variable type, for example:
var data *int // 声明一个int类型指针变量data data = new(int) // 通过new函数在堆上分配一个整型数据内存,并将data指向这段内存
Through the above code, we successfully created a memory on the heap An integer data memory is allocated and its address is assigned to the data pointer variable. Next, we can assign and access data through the following code:
*data = 100 // 赋值操作,将整型数据100赋值给指针data指向的内存 fmt.Println(*data) // 访问操作,打印指针data指向的内存中存储的数据,即100
It should be noted that in Golang, the new keyword returns a pointer type corresponding to a variable type. For example, when passing new(int) to a function, what is actually passed is a pointer value of type int. When using it, you need to dereference this pointer with the * operator.
In addition to basic data types, the new keyword can also be used to create instances of user-defined types. For example, below we define a structure type Person, which contains two member variables: name and age. Then we create an instance of this type through the new keyword and assign values to the member variables.
type Person struct { name string age int } p := new(Person) p.name = "joseph" p.age = 30 fmt.Println(p)
Through the above code, we successfully created an instance for the Person type and successfully performed member variable assignment and printing operations. It should be noted that in Golang, structure member variables can be accessed in two ways: p.name and (*p).name. The former is a simple way of writing, and Golang will automatically convert it into the latter's dereference way of writing. Therefore both are equivalent.
To sum up, the new keyword is a very convenient and practical memory allocation tool in Golang. It can quickly allocate memory for variable types on the heap with one line of code and initialize it to zero value. By using the new keyword appropriately, we can perform memory management quickly and efficiently in Golang.
The above is the detailed content of golang new usage. For more information, please follow other related articles on the PHP Chinese website!