golang中[] string和... string之间有什么区别? [英] What is the difference between []string and ...string in golang?

查看:61
本文介绍了golang中[] string和... string之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go语言中,

[] string 是一个字符串数组

,我们还使用 ... string 作为参数.

and we also use ...string as a parameter.

有什么区别?

函数定义:

func f(args ...string) {}

我可以像下面这样调用此函数吗?

Can I call this function like below?

args := []string{"a", "b"}

f(args)

推荐答案

[] string 是一个字符串数组

从技术上讲,这是一个引用基础数组的切片

Technically it's a slice that references an underlying array

,我们还使用 ... string 作为参数.

有什么区别?

关于结构,什么都没有.两种语法得出的数据类型是相同的.

With respect to the structure, nothing really. The data type resulting from both syntax is the same.

... 参数语法构成可变参数.它将接受零个或多个 string 参数,并将它们作为切片引用.

The ... parameter syntax makes a variadic parameter. It will accept zero or more string arguments, and reference them as a slice.

关于调用 f ,您可以使用以下语法将字符串的一部分传递给可变参数:

With respect to calling f, you can pass a slice of strings into the variadic parameter with the following syntax:

func f(args ...string) {
    fmt.Println(len(args))
}


args := []string{"a", "b"}

f(args...)

此语法可用于使用文字语法构建的切片,或表示可变参数的切片(因为它们之间确实没有区别).

This syntax is available for either the slice built using the literal syntax, or the slice representing the variadic parameter (since there's really no difference between them).

http://play.golang.org/p/QWmzgIWpF8

这篇关于golang中[] string和... string之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆