golang中[]字符串和...字符串有什么区别? [英] what is difference between []string and ...string in golang?

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

问题描述

在Go语言中



[]字符串是字符串数组

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

有什么区别?



函数定义:

  func f(args ... string){} 

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

  args:= [] string {a,b} 

f(args)


解决方案


[] string 是字符串数组

从技术上讲,它是一个引用底层数组的切片


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

有什么区别?


关于结构,没有什么是真的。这两种语法产生的数据类型是相同的。

... 参数语法提供了一个可变参数。它会接受零个或多个字符串参数,并将它们作为切片引用。



关于调用 f ,您可以使用以下语法将一段字符串传递到variadic参数中:

  fmt.Println(len(args))
}


args:= [] string { a,b}

f(args ...)

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

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


in Go language

[]string is string array

and we also use ...string as parameter

what is difference?

function definition:

func f(args ...string) {}

and can i call this function like below?

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

f(args)

解决方案

[]string is string array

Technically it's a slice that references an underlying array

and we also use ...string as parameter

what is difference?

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

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

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中[]字符串和...字符串有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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