Go equivalent of PHP's 'implode'
Asked Answered
R

4

47

What is the Go equivalent of PHP's 'implode'?

Responsiveness answered 23/8, 2012 at 9:40 Comment(2)
stackoverflow.com/tags/go/infoResponsiveness
en.wikipedia.org/wiki/Go_%28programming_language%29Lukewarm
S
72

In the standard library: strings.Join

func Join(a []string, sep string) string

http://golang.org/pkg/strings/#Join

Cheers!

Syringe answered 23/8, 2012 at 9:44 Comment(1)
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.Responsiveness
T
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, ", "))
Tother answered 23/8, 2012 at 9:45 Comment(0)
C
7
s := []string{"this", "is", "a", "joined", "string\n"};
strings.Join(s, " ");

Did this help you?

Compurgation answered 23/8, 2012 at 9:46 Comment(0)
A
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)
}
Artilleryman answered 5/6, 2016 at 14:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.