How to use the new function in the Go language?
In Go language, ‘new’ is a built-in function used to create a pointer to a zero value of a specified type.
The syntax for using the new function is as follows:
ptr := new(Type)
Type is the type to be created, while ptr is a pointer to that type.
Here is an example of creating a pointer using the new function.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
// 使用new函数创建Person类型的指针
p := new(Person)
// 使用指针访问结构体字段,并赋值
p.Name = "Alice"
p.Age = 20
// 打印结构体指针的值
fmt.Println(p)
}
The output is:
&{Alice 20}
In this example, we created a pointer p to a Person type using new(Person). We then accessed the struct fields using the pointer and assigned values to them. Finally, when we printed the value of the struct pointer, we could see that the pointer pointed to a struct object with the specified field values.