Getting started with Golang: The reason why the copy function does not work, lightning protection.

In the following code, there is nothing in the output, but the copy function is indeed executed, so why is this?

	var iArray1 = []int{0, 1, 2, 3, 4, 5, 6}
	var iArray2  []int
	copy(iArray2, iArray1)
	for _, v := range iArray2 {
		fmt.Printf("v: %v\n", v)
	}

After consulting the data, I found that the original copy() in go is to copy according to the number of elements of the smaller array slice. So the reason why the above execution has no results is that the slice named iArray2 has no initial value and no defined length after definition, so the default is 0, so although iArray1 is copied to iArray2, only 0 is copied, so there is no output result.

Then let's modify it and give iArray2 an initial length.

Look carefully at the position of my red arrow, give iArray2 ten lengths, then execute copy(), and copy iArray1 to iArray2. After finding the output, the copy was indeed successful, but the following items are all 0. The reason is still, because iArray1 only copies seven values ​​to iArray2, so the remaining three values ​​in iArray1 are not overwritten, and they are still 0 by default.

copy() can also be used like this

The grammar in the go language is really a lot of small details, very ingenious, and friends who are learning together are welcome to discuss it together.

Guess you like

Origin blog.csdn.net/weixin_45963929/article/details/126103236