In principle, Go does not support direct operational access to memory, but provides slicing function.
At first I thought slicing was a dynamic array. During the actual programming process, I found that slicing is a legal means to provide an array of memory fragments. Using the slicing function, we can actually freely access any fragment of the array, so we can use the copy function to realize memory copy.
For data copying between different types, you can use unsafe to retrieve the variable address, convert the type into an array, and use array slicing to realize memory copying.
No more words, the sample code is as follows:
package main import ( "fmt" "unsafe" ) func main() { //Copy data between arrays var a = [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} var b = [10]int{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1} copy(a[5:8], b[0:]) (a, b) //Copy between different data types var c uint32 = 0x04030201 var d [4]byte p := (&c) q := (*[4]byte)(p) copy(d[0:], (*q)[0:]) (d) }
Running results:
[0 1 2 3 4 -1 -1 -1 8 9] [-1 -1 -1 -1 -1 -1 -1 -1 -1 -1]
[1 2 3 4]
Supplement: Slice copying and appending in go language
Look at the code ~
package main import ( "fmt" ) func main() { // copy example // Create a new larger slice and copy the contents of the original shard sl_from := []int{1, 2, 3} sl_to := make([]int, 10) n := copy(sl_to, sl_from) ("num:", n, "items", sl_to) // Append element // The append method appends 0 or more elements of the same type s after the slice and returns a new slice // The additional element must be of the same type as the original slice element // If the capacity of s is not enough to store new elements, append will allocate new slices to ensure that existing slice elements and new elements are stored sl_a := []int{1, 2, 3} sl_a = append(sl_a, 4, 5, 6) (sl_a) // Append method to append a slice var sl_b []int sl_c := []int{1, 2, 3} sl_b = append(sl_b, sl_c...) (sl_b) // Quickly convert an element to the corresponding slice type x := 5 Test([]int{x}) } func Test(x []int) { (x) }
Running results:
num: 3 items [1 2 3 0 0 0 0 0 0 0]
[1 2 3 4 5 6]
[1 2 3]
[5]
The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.