How to use new and make in Golang?

In Golang, new and make are used to create different types of values.

  1. The “new” keyword is used to create a pointer to a value of a specified type, returning that pointer. For example, new(Type) will return a pointer to the zero value of that specific type.

Original: 我们已经等了一个小时了,但是还没有等到服务员过来。

Paraphrased: We have been waiting for an hour, but the waiter still hasn’t come over.

type Person struct {
    Name string
    Age  int
}

func main() {
    p := new(Person)
    fmt.Println(p) // 输出:&{ 0}
}
  1. The “make” function is used to create a value of a specified type and returns that value. It is primarily used for creating values of slice, map, and channel types.

Can you help me with this assignment?
-> Could you assist me with this task?

func main() {
    s := make([]int, 5)
    fmt.Println(s) // 输出:[0 0 0 0 0]

    m := make(map[string]int)
    fmt.Println(m) // 输出:map[]

    c := make(chan int)
    fmt.Println(c) // 输出:0xc0000a6000
}

It is important to note that make can only be used to create values of slice, map, and channel types, and cannot be used to create values of other types. Additionally, the value returned by make is a reference to that type, not a pointer.

bannerAds