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 参数传递
本文路径:https://www.cdcxhl.com/article40/hhgpeo.html

成都网站建设公司_创新互联,为您提供商城网站品牌网站制作网站导航建站公司企业建站域名注册

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

外贸网站制作