go built-in functions

append function

  1. usage
    • append is mainly used to append elements to a slice (slice)
    • If the slice storage space (cap) is sufficient, it will be appended directly, and the length (len) will become longer; if the space is insufficient, the memory will be re-opened, and the previous elements and new elements will be copied into it
    • The first parameter is a slice, followed by a variable parameter that stores the element type of the slice
    • The second parameter can also directly write another slice, and append all copies of the elements in it to the first slice. It should be noted that the parameters of this usage function can only receive two slices, and three dots must be added at the end
    • There is also a special usage, passing in a string as a []byte type as the second parameter
    • The return value of the append function must be received by a variable, otherwise the compiler will report an error
  2. Example
var s = make([]int, 3, 5)
f.Printf("%p", s)
f.Println()
s = append(s, 1)

slice := append([]int{1,2,3},[]int{4,5,6}...)
fmt.Println(slice) //[1 2 3 4 5 6]

bytes := append([]byte("hello"),"world"...)

make and new functions


  1. new function
    • new is a built-in function, and the function prototype is
    • function prototype

func new(Type) *Type

  • What is passed to the new function is a type, not a value. The return value is a pointer to this newly allocated zero value.
  • make function
    • Its function prototype has one more (length) parameter than new, and the return value is also different.
      func make(Type, size IntegerType) Type
    • The first parameter is a type, the second parameter is the length, and the return value is a type
    • The built-in function make allocates and initializes a ==slice==, or ==map== or ==chan== object. And only these three objects.
    • The first parameter is a type, not a value. But the return value of make is this type (even a reference type), not a pointer. The specific return value depends on the specific incoming type.
  • Summarize
    • The role of new is to initialize a pointer to a type (*T), the role of make is to initialize a slice, map or channel, and return a reference T
    • ==Array [created in a normal way]==, ==Array pointer [new]==, ==Slice [make]== Concept
  • Guess you like

    Origin http://43.154.161.224:23101/article/api/json?id=325983103&siteId=291194637