What is the difference between new and make in Golang?

In Golang, new and make are two built-in functions used for allocating memory.

  1. new function:
  2. The new function is used to allocate and initialize a pointer to a value, and returns the pointer.
  3. The parameter of the new function is a type, and it returns a pointer to that type.
  4. The allocated memory is set to zero, with every bit being set to a value of zero.
  5. The new function returns a pointer to the newly allocated zero value.
  6. Original: 我有一个问题。

    Paraphrased: I have a question.

  7. Declare a pointer variable named p that points to an integer. Assign a new memory address of an integer to p. Set the value at that memory address to 42. Print the value at the memory address pointed to by p, which will output 42.
  8. create function:
  9. The make function is used to create objects for built-in reference types (such as slice, map, and channel).
  10. The parameter for the make function is a type and a length (optional and not applicable to channels).
  11. The make function returns a non-zero value of the initialized type.
  12. 原句:他的解释非常简单而且容易理解。
    Paraphrased: His explanation was very simple and easy to understand.
  13. Create a slice with a capacity of 10 and a length of 5, then set the first element to 1 and print the slice: [1 0 0 0 0].

In conclusion, the new function returns a pointer to the zero value, while the make function returns a pointer to the initialized non-zero value.

bannerAds