The append feature in the Go language is very powerful, and using it can make the implementation of many functions more concise. The following is a simple comparison:
. Insert one slice into another slice at the specified location:
Do not use append:
Func Insertsliceatindex (Slice_origin []int, Slice_to_insert []int,
insertindex int) (result []int, err error) {
If Insertindex > Len (slice_origin) {
return nil, errors. New ("Insertindex cannot be greater than Slice_origin length")
}
result = make ([]int, Len (slice_origin) +len (Slice_to_insert))
For I: = 0; I < Len (result); i++ {
If I < Insertindex {///insertion point
result[i] = slice_origin[i]
} else if I < Insertindex+len (slice_to_in SERT) {//insert content
result[i] = Slice_to_insert[i-insertindex]
} else {
result[i] = Slice_origin[i-len (slice_ To_insert)]
}
}
return
}
When using append, the code is very concise:
D: = []string{"Welcome", "for", "Tianjin", "has", "a", "good", "Journey"}
insertslice: = []string{"It", "is", "a", "B" IG "," City "}
Insertsliceindex: = 3
D = Append (D[:insertsliceindex],
append (Insertslice, d[ Insertsliceindex:] ...) ...)
Fmt. Printf ("result:%v\n", D)