pass constant list (immutable) in variadic in Go

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

pass constant list (immutable) in variadic in Go

问题

var state = [...]string{
	"new",
	"submitted",
	"approved",
	"rejected",
}

In(values ...interface{}) {
  return
}

我需要在Go语言中将一个不可变列表传递给一个可变参数函数。

英文:
var state = [...]string{
	"new",
	"submitted",
	"approved",
	"rejected",
}

In(values ...interface{}) {
  return
}

I need to pass an immutable list to a variadic function in go

答案1

得分: 3

你不能将字符串的切片或数组传递给接受可变参数列表的函数,该函数的参数类型为interface{}。你需要先创建一个[]interface{},然后将其传递进去:

args := make([]interface{}, len(state))
for i, x := range state {
   args[i] = x
}
In(args...)
英文:

You cannot pass a slice or array of strings to a function that accepts a variadic argument list of interface{} types. You have to first create an []interface{}, and pass that:

args:=make([]interface{},len(state))
for i,x:=range state {
   args[i]=x
}
In(args...)

huangapple
  • 本文由 发表于 2022年12月13日 14:36:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/74780837.html
匿名

发表评论

匿名网友

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

确定