Simple operations of Golang arrays to merge arrays and delete the value of an index

Simple operations of Golang arrays to merge arrays and delete the value of an index

Golang easy to learn


1. What is an interface array ([]interface{})?

When passing a value to the []interface{} function, the Go runtime will perform type conversion (if necessary) and convert the value to a value of type interface{}. All values ​​have only one type at runtime, and a static type of v is interface{}.

2. Detailed code

1. Merge arrays

The code is as follows (example):

// MergeArray 合并数组
func MergeArray(dest []interface{
    
    }, src []interface{
    
    }) (result []interface{
    
    }) {
    
    
	result = make([]interface{
    
    }, len(dest)+len(src))
	//将第一个数组传入result
	copy(result, dest)
	//将第二个数组接在尾部,也就是 len(dest):
	copy(result[len(dest):], src)
	return
}

2. Delete an index in the array

The code is as follows (example):

// DeleteIndex 删除数组
func DeleteIndex(src []interface{
    
    }, index int) (result []interface{
    
    }) {
    
    
	// 删除 也就是将该之前与之后的数组合并成新数组
	result = append(src[:index], src[(index+1):]...)
	return
}

3. Complete code

The code is as follows (example):

package main

import (
	"fmt"
)

func main() {
    
    

	//建立数组1
	list1 := []interface{
    
    }{
    
    
		"1", "2",
	}
	//建立数组2
	list2 := []interface{
    
    }{
    
    
		"3", "4",
	}

	fmt.Println(MergeArray(list1, list2))

	fmt.Println(DeleteIndex(list1, 1))

}

// MergeArray 合并数组
func MergeArray(dest []interface{
    
    }, src []interface{
    
    }) (result []interface{
    
    }) {
    
    
	result = make([]interface{
    
    }, len(dest)+len(src))
	//将第一个数组传入result
	copy(result, dest)
	//将第二个数组接在尾部,也就是 len(dest):
	copy(result[len(dest):], src)
	return
}

// DeleteIndex 删除数组
func DeleteIndex(src []interface{
    
    }, index int) (result []interface{
    
    }) {
    
    
	// 删除 也就是将该之前与之后的数组合并成新数组
	result = append(src[:index], src[(index+1):]...)
	return
}


Summarize

Easily understand the simple way to interface arrays in Golang to reduce the time of reinventing the wheel in your usual work.

Hope this blog will be useful to you. I am the King of Light, and I speak for myself.

Guess you like

Origin blog.csdn.net/moer0/article/details/123142225