Go解包数组作为参数

huangapple go评论114阅读模式
英文:

Go Unpacking Array As Arguments

问题

在Python和Ruby中,有一个用于将数组解包为参数的星号操作符(*)。在Javascript中,有一个.apply()函数。在Go语言中,有没有一种将数组/切片解包为函数参数的方法?如果有的话,希望能提供一些相关资源!

类似于以下代码:

func my_func(a, b int) (int) {
    return a + b
}

func main() {
    arr := []int{2,4}
    sum := my_func(arr)
}
英文:

So in Python and Ruby there is the splat operator (*) for unpacking an array as arguments. In Javascript there is the .apply() function. Is there a way of unpacking an array/slice as function arguments in Go? Any resources for this would be great as well!

Something along the lines of this:

func my_func(a, b int) (int) {
    return a + b
}

func main() {
    arr := []int{2,4}
    sum := my_func(arr)
}

答案1

得分: 262

你可以使用类似于C语言的可变参数语法:

package main
import "fmt"

func my_func(args ...int) int {
   sum := 0
   for _, v := range args {
      sum = sum + v
   }

   return sum;
}

func main() {
    arr := []int{2, 4}
    sum := my_func(arr...)
    fmt.Println("Sum is ", sum)
}

现在你可以对任意数量的东西求和。注意在调用my_func函数时重要的...

运行示例:http://ideone.com/8htWfx

英文:

You can use a vararg syntax similar to C:

package main
import "fmt"

func my_func( args ...int) int {
   sum := 0
   for _,v := range args {
      sum = sum + v
   }

   return sum;
}

func main() {
    arr := []int{2,4}
    sum := my_func(arr...)
    fmt.Println("Sum is ", sum)
}

Now you can sum as many things as you'd like. Notice the important ... after when you call the my_func function.

Running example: http://ideone.com/8htWfx

答案2

得分: 18

如果你的函数是可变参数的,你可以像Hunter McMillen展示的那样使用带有...符号的切片,或者如果你的函数有固定数量的参数,你可以在编写代码时解包它们。

如果你真的想在具有固定数量参数的函数上动态执行此操作,你可以使用反射:

package main
import "fmt"
import "reflect"

func my_func(a, b int) (int) {
    return a + b
}

func main() {
    arr := []int{2,4}
    var args []reflect.Value
    for _, x := range arr {
        args = append(args, reflect.ValueOf(x))
    }
    fun := reflect.ValueOf(my_func)
    result := fun.Call(args)
    sum := result[0].Interface().(int)
    fmt.Println("Sum is ", sum)
}
英文:

Either your function is varargs, in which you can use a slice with the ... notation as Hunter McMillen shows, or your function has a fixed number of arguments and you can unpack them when writing your code.

If you really want to do this dynamically on a function of fixed number of arguments, you can use reflection:

package main
import "fmt"
import "reflect"

func my_func(a, b int) (int) {
    return a + b
}

func main() {
    arr := []int{2,4}
    var args []reflect.Value
    for _, x := range arr {
        args = append(args, reflect.ValueOf(x))
    }
    fun := reflect.ValueOf(my_func)
    result := fun.Call(args)
    sum := result[0].Interface().(int)
    fmt.Println("Sum is ", sum)
}

答案3

得分: -4

func unpack(a map[string]string) string {

var stmt, val string
var x, y []string
for k, v := range a {
	x = append(x, k)
	y = append(y, "'" + v + "'")
}

stmt = "INSERT INTO tdo.rca_trans_status (" + strings.Join(x, ", ")
val = ") VALUES (" + strings.Join(y, ",") + ");"

return stmt + val

}

英文:

https://play.golang.org/p/2nN6kjHXIsd

I had a reason to unpack some vars from a map[string]string with single quotes around some of them as well as without. Here's the logic for it and the play link up top has the full working snippet.

func unpack(a map[string]string) string {

var stmt, val string
var x, y []string
for k, v := range a {
	x = append(x, k)
	y = append(y, "'"+v+"'")
}

stmt = "INSERT INTO tdo.rca_trans_status (" + strings.Join(x, ", ")
val = ") VALUES (" + strings.Join(y, ",") + ");"

return stmt + val}

Which presents cleanly for a mssql query as:

INSERT INTO tdo.rca_trans_status (rca_json_body, original_org, md5sum, updated, rca_key) VALUES ('blob','EG','2343453463','2009-11-10 23:00:00','prb-180');

答案4

得分: -26

不,语言中没有直接支持这个的功能。Python、Ruby以及你提到的Javascript都是动态/脚本语言。Go更接近于C,而不是任何动态语言。"apply"功能对于动态语言很方便,但对于像C或Go这样的静态语言几乎没有用处。

英文:

No, there's no direct support for this in the language. Python and Ruby, as well as Javascript you're mentioning; are all dynamic/scripting languages. Go is way closer to, for example, C than to any dynamic language. The 'apply' functionality is handy for dynamic languages, but of little use for static languages like C or Go,

huangapple
  • 本文由 发表于 2013年7月10日 02:45:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/17555857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定