4
4
4utka_pyan2017-06-23 14:05:47
go
4utka_pyan, 2017-06-23 14:05:47

How to properly concatenate strings in golang?

I saw a similar question in ang stack, but an attempt to implement it resulted in an error:
miltiple-value buffer.WriteString() in single-value context
The code was like this

package main
import (
  "fmt"
  "bytes"
)
func main() {
  var x []string
  letter := [3]string{"a","б","в"}
  
    for i := 0; i < len(letter); i++ {
    var buffer bytes.Buffer
    x = append(x, buffer.WriteString(letter[i]))
    }
  fmt.Println(x)
}

Then I used an example from the site gobyexample https://play.golang.org/p/l4b7MPT4u6
package main
import "strings"
import "fmt"
func main() {
  var x []string
  letter := [3]string{"a","б","в"}
  
    for i := 0; i < len(letter); i++ {
    var z string = ""
    x = append(x, z.Join([]string{"a", "b"}, "-"))
    }
  fmt.Println(x)
}

It's not clear at all, firstly, he says that I am importing but not using the strings package
Secondly, z.Join is undefined (type string has no field or method Join) or does he not see the method because I have go version 1.6? Although the docs https://golang.org/pkg/strings/#Join do not say anything about which version it starts with...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
chupasaurus, 2017-06-23
@4utka_pyan

You do not call strings.Join(), the correct option is:

func main() {
  var x []string
  letter := [3]string{"a","б","в"}
  
    for i := 0; i < len(letter); i++ {
    x = append(x, strings.Join([]string{"a", "b"}, "-"))
    }
  fmt.Println(x)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question