资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

go语言中参数传递 golang 参数传递

Go 函数参数传递详解

前言:go语言函数参数为值拷贝(指针参数为指针拷贝)。

成都创新互联成立于2013年,先为巫溪等服务建站,巫溪等地企业,进行企业商务咨询服务。为巫溪企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

在go语言中,函数也作为一种数据类型,所以函数也可以作为函数的参数来使用。

其中slice是为地址数组指针的拷贝⚠️,持续更新中 ....

golang的不定参数怎么传递下去

给你个fmt.Printf的例子:

echo 函数不定参数,其调用fmt.Printf进行输出,因为v是一个slice,所以传递给fmt.Printf的时候需要 v...,就类似append(slice1,slice2...)

package main

import (

"fmt"

)

func main() {

echo("Hello %s, I am %s\n", "Bob", "John")

}

func echo(format string, v ... interface{}) {

fmt.Printf(format, v...)

}

golang-101-hacks(12)——切片作为函数参数传递

注:本文是对 golang-101-hacks 中文翻译。

在Go语言中,函数参数是值传递。使用slice作为函数参数时,函数获取到的是slice的副本:一个指针,指向底层数组的起始地址,同时带有slice的长度和容量。既然各位熟知数据存储的内存的地址,现在可以对切片数据进行修改。让我们看看下面的例子:

In Go, the function parameters are passed by value. With respect to use slice as a function argument, that means the function will get the copies of the slice: a pointer which points to the starting address of the underlying array, accompanied by the length and capacity of the slice. Oh boy! Since you know the address of the memory which is used to store the data, you can tweak the slice now. Let's see the following example:

运行结果如下

由此可见,执行modifyValue函数,切片s的元素发生了变化。尽管modifyValue函数只是操作slice的副本,但是任然改变了切片的数据元素,看另一个例子:

You can see, after running modifyValue function, the content of slice s is changed. Although the modifyValue function just gets a copy of the memory address of slice's underlying array, it is enough!

See another example:

The result is like this:

而这一次,addValue函数并没有修改main函数中的切片s的元素。这是因为它只是操作切片s的副本,而不是切片s本身。所以如果真的想让函数改变切片的内容,可以传递切片的地址:

This time, the addValue function doesn't take effect on the s slice in main function. That's because it just manipulate the copy of the s, not the "real" s.

So if you really want the function to change the content of a slice, you can pass the address of the slice:

运行结果如下

【Go参数传递:值类型、引用类型和指针类型】

修改参数

值类型

指针类型

引用类型

chan

类型零值

总结 :在Go语言中, 函数的参数传递只有值传递 ,而且传递的实参都是原始数据的一份拷贝。如果拷贝的内容是值类型的,那么在函数中无法修改原始数据,如果拷贝的内容是指针(或者可以理解为引用类型),那么可以在函数中修改原始数据。


网页题目:go语言中参数传递 golang 参数传递
文章链接:http://cdkjz.cn/article/hhgpeo.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220