意思是源和目标可以为同一目标,复制的数量是源或者目标的元素最小数量
比如例子中的copy(s,a[0]:)
a虽然一共有8个元素,但是s只有6<len(det)>个元素 ,看上面的makeint是6
所以这里只复制了最小数量6个元素,因此a的012345被复制进了s
第二个
copy(s,s[2]:)
这里是从s[2]开始,所以len是6-2=4,而且因为4<6,只复制4个元素
因此
0 1 2 3 4 5 复制后4个元素到前面结果就是:
2 3 4 5 4 5 //这个就是可以源和目标可重叠,
上面的也说明了按照len(str)和len(det)中最少值
在 Go 语言中,结构体是一种值类型,当传递结构体参数时,会进行值拷贝。如果结构体字段是小写的,它们在外部是不可见的,不能被读取或者访问,因此我们必须对字段进行大写。在 unmarshal 函数中,读取的是 JSON 或者 XML 等格式的数据,需要映射到结构体字段中。如果字段为大写,它们就可以被外部的 unmarshal 函数读取,否则无法访问这些字段。因此,将结构体字段大写变成了一种规范,以保证结构体字段可以被 unmarshal 函数读取。
按值传递函数参数,是拷贝参数的实际值到函数的形式参数的方法调用。在这种情况下,参数在函数内变化对参数不会有影响。默认情况下,Go编程语言使用调用通过值的方法来传递参数。在一般情况下,这意味着,在函数内码不能改变用来调用所述函数的参数。考虑函数swap()的定义如下。
代码如下:
/* function definition to swap the values */
func swap(int x, int y) int {
var temp int
temp = x /* save the value of x */
x = y/* put y into x */
y = temp /* put temp into y */
return temp
}
现在,让我们通过使实际值作为在以下示例调用函数swap():
代码如下:
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100
var b int = 200
fmt.Printf("Before swap, value of a : %d\n", a )
fmt.Printf("Before swap, value of b : %d\n", b )
/* calling a function to swap the values */
swap(a, b)
fmt.Printf("After swap, value of a : %d\n", a )
fmt.Printf("After swap, value of b : %d\n", b )
}
func swap(x, y int) int {
var temp int
temp = x /* save the value of x */
x = y/* put y into x */
y = temp /* put temp into y */
return temp
}
让我们把上面的代码放在一个C文件,编译并执行它,它会产生以下结果:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
这表明,参数值没有被改变,虽然它们已经在函数内部改变。
通过传递函数参数,即是拷贝参数的地址到形式参数的参考方法调用。在函数内部,地址是访问调用中使用的实际参数。这意味着,对参数的更改会影响传递的参数。
要通过引用传递的值,参数的指针被传递给函数就像任何其他的值。所以,相应的,需要声明函数的参数为指针类型如下面的函数swap(),它的交换两个整型变量的值指向它的参数。
代码如下:
/* function definition to swap the values */
func swap(x *int, y *int) {
var temp int
temp = *x/* save the value at address x */
*x = *y /* put y into x */
*y = temp/* put temp into y */
}
现在,让我们调用函数swap()通过引用作为在下面的示例中传递数值:
代码如下:
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100
var b int= 200
fmt.Printf("Before swap, value of a : %d\n", a )
fmt.Printf("Before swap, value of b : %d\n", b )
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b)
fmt.Printf("After swap, value of a : %d\n", a )
fmt.Printf("After swap, value of b : %d\n", b )
}
func swap(x *int, y *int) {
var temp int
temp = *x/* save the value at address x */
*x = *y/* put y into x */
*y = temp/* put temp into y */
}
让我们把上面的代码放在一个C文件,编译并执行它,它会产生以下结果:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
这表明变化的功能以及不同于通过值调用的外部体现的改变不能反映函数之外。