go study notes--majority combination

go study notes--majority combination

 

The go language itself does not have a function similar to array_merge in php, and it cannot directly merge multiple arrays, 
but this type of operation is really common in daily development. 
There are two ways to complete this operation.

1: The append() 
function can certainly complete the above operations, but using append means traversing the array, which means that the dynamic expansion of the slice length 
can only be said to be stupid 
2: copy() 
func copy

func copy(dst, src []Type) int

The copy built-in function copies elements from a source slice into a destination slice. (As a special case, it also will copy bytes from a string to a slice of bytes.) The source and destination may overlap. Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

So be sure to prevent overlapping when using copy

The specific content is not repeated, the above code:

package tool



type CommonFunc struct{}


var commonFunc CommonFunc


func (c *CommonFunc) Merge(s ...[]interface{}) (slice []interface{}) {
    switch len(s) {
    case 0:
        break
    case 1:
        slice = s[0]
        break
    default:
        s1 := s[0]
        s2 := commonFunc.Merge(s[1:]...)//...将数组元素打散
        slice = make([]interface{}, len(s1)+len(s2))
        copy(slice, s1)
        copy(slice[len(s1):], s2)
        break
    }


    return
}

Guess you like

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