How to Join an Array of Strings into a Single String in Go

To join an array of strings into a single string in Go, you must convert an array to a slice using [:] and then use the strings.Join() function to join the slice elements into a single string.

package main

import (
  "fmt"
  "strings"
)

func main() {
  // Define an array of strings
  wordsArray := [2]string{"GPT-4", "Bard"}

  // Convert the array to a slice
  wordsSlice := wordsArray[:]

  // Join the slice of strings using a space separator
  joined := strings.Join(wordsSlice, " ")

  fmt.Println("Joined string:", joined)
}

Output

Joined string: GPT-4 Bard

In this example, we have an array of strings called wordsArray.

We converted the array to a slice called wordsSlice using the [:] expression.

In the next step, we used the strings.Join() function to join the slice elements with a space separator and store the result in the joined variable.

Finally, we printed the joined string.

That’s it.

Leave a Comment