the role of the APPEND functionOfficial explanation The Append function is to append one or more elements to the slice and then return a slice of the same type as slice, whose signature is
Func Append (slice []t, elements ... T) []t
What append does is add the element at the end of the slice and return the result. The result needs to be returned because, as we handwritten Append, the underlying array may change. Examples of Use:
x: = []int{1,2,3}
x = Append (x, 4, 5, 6)
FMT. PRINTLN (x)
Print output value 1 2 3 4 5
pits using the processThe following pits are used in the process:
var cateout []*category
var Cate []*category={cate1,cate2,...., cate10}//already initialized good value for
j: = 0; J <
Cateout = Append (Cateout, cate[i])
}
The above code runs out of the value of the cateout result of 10 cate[9], where category is a struct, but the desired result is cateout full copy cate value, pit .... Solution, add the temporary variable temp to the above code, which is:
var cateout []*category
var Cate []*category={cate1,cate2,...., cate10}//already initialized good value for
j: = 0; J <
var temp *category
temp=cate[i]
cateout = append (cateout, temp)
}
The magic of the problem solved, a face Meng ... Preliminary analysis: It should be necessary to create a new temp variable at the time of the For loop, and use this clean temporary variable to fetch the value and assign it to cateout.
Summary: If you do not use the temp, then each assignment to Cateout's cate[i] itself is an address, such as "AAA", the address itself has not changed, the change is only the object of this address point, so the original Cateout result value will be [aaa],[aaa AAA],[AAA AAA AAA] ... That is, each time an identical address value is added, but the value that the address AAA points to during the subsequent run has changed, so the result is wrong. But using temp is different, each time a new variable value is generated, the new address is assigned to it, the cateout result value will be [aaa],[aaa bbb],[aaa BBB CCC] ..., so that even if cate[i] this address points to the value of the change, It will not affect the final result.