string
A slice contains string
data. It contains int
data. With strings.Join
we can convert a string
slice to a string
.
For slices with ints, or other types of elements, we can first convert a slice into a string
slice. A method like strconv.Itoa
can help.
String
sliceHere we convert a string
slice into a string
. Our string
slice has three elements. More can be added with append()
.
strings.Join
, we combine all elements of a string
slice into a string
.strings.Join
is the delimiter. For no delimiter, please use an empty string
literal.package main import ( "fmt" "strings" ) func main() { values := []string{"one", "two", "three"} // Convert string slice to string. // ... Has comma in between strings. result1 := strings.Join(values, ",") fmt.Println(result1) // ... Use no separator. result2 := strings.Join(values, "") fmt.Println(result2) }one,two,three onetwothree
Int
slice to string
Here we convert an int
slice into a string
. First we create a string
slice from the data in the int
slice. We use a for-range
loop for this.
Itoa()
converts an int
into a string
. We then place these strings (text) into the valuesText
slice.string
slice into a string
with the strings.Join
method.package main import ( "fmt" "strconv" "strings" ) func main() { // The int slice we are converting to a string. values := []int{10, 200, 3000} valuesText := []string{} // Create a string slice using strconv.Itoa. // ... Append strings to it. for i := range values { number := values[i] text := strconv.Itoa(number) valuesText = append(valuesText, text) } // Join our string slice. result := strings.Join(valuesText, "+") fmt.Println(result) }10+200+3000
Append
runesIn Go we have another option for building up a string
. We can append runes to a rune
slice based on our data. Then we can convert the rune
slice into a string
.
With strings.Join
we convert a string
slice into a string
. Sometimes we can convert another type of data, like an int
slice, into a string
slice before using Join
.