What is the Go equivalent of PHP's 'implode'?
            Asked
            
        
        
            Active
            
        
            Viewed 2.4k times
        
    43
            
            
        - 
                    http://stackoverflow.com/tags/go/info – code_martial Aug 23 '12 at 09:43
- 
                    http://en.wikipedia.org/wiki/Go_%28programming_language%29 – Dmytro Zarezenko Aug 23 '12 at 09:43
4 Answers
70
            In the standard library: strings.Join
func Join(a []string, sep string) string
http://golang.org/pkg/strings/#Join
Cheers!
 
    
    
        thwd
        
- 23,956
- 8
- 74
- 108
- 
                    Thanks a lot! I spent about half an hour searching for this and stackoverflow got me the answer in less than 5 minutes! OTOH, I now feel a bit dumb to not have browsed through the "strings" package documentation. – code_martial Aug 23 '12 at 09:48
13
            
            
        Join in the strings library. It requires the input array to be strings only (since Go is strongly typed).
Here is an example from the manual:
s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
 
    
    
        Emil Vikström
        
- 90,431
- 16
- 141
- 175
7
            
            
        s := []string{"this", "is", "a", "joined", "string\n"};
strings.Join(s, " ");
Did this help you?
 
    
    
        Musa
        
- 96,336
- 17
- 118
- 137
 
    
    
        Matti Simperi
        
- 177
- 4
4
            
            
        As i remember, PHP don't have strict typing. Probably not worst idea to use something like this.
package main
import (
    "fmt"
    "strings"
)
func Implode(glue string, args ...interface{}) string {
    data := make([]string, len(args))
    for i, s := range args {
        data[i] = fmt.Sprint(s)
    }
    return strings.Join(data, glue)
}
type S struct {
    z float64
}
func main() {
    v := Implode(", ", 1, "2", "0.2", .1, S{});
    fmt.Println(v)
}
 
    
    
        Iveronanomi
        
- 89
- 5
