A
A
Alexander Shpak2015-08-02 14:35:51
go
Alexander Shpak, 2015-08-02 14:35:51

How to pass an array []string to a function that accepts ... string?

Actually the question is in the title.
If I pass it directly, then when the program is executed, something like this comes out:
panic: sql: expected 4 arguments, got 1

Answer the question

In order to leave comments, you need to log in

2 answer(s)
X
xotkot, 2015-08-02
@shpaker

If I understand correctly, something like this:

func add(args ...string) (total string) {
  for _, v := range args {
    total += v
  }
  return
}

func main() {
  fmt.Println(add("1", "2", "3"))   // 123

  xs := []string{"1", "2", "3"}
    fmt.Println(add(xs...))        // 123
}

put an array and three dots at the end, in this example it's xs...

F
FanKiLL, 2015-08-02
@FanKiLL

...string
Means that you want to pass an indefinite number of parameters with type string
for example concatenation

func Concat(strings ...string) bytes.Buffer {
  buffer := bytes.Buffer{}
  for _, str := range strings {
    buffer.WriteString(str)
  }
  return buffer
}

And you need to call accordingly
Concat("Строка 1", "Строка 2", "Строка 3", "Строка 4", "Строка 5")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question