Go equivalent of PHP's 'implode'-ThrowExceptions

Exception or error:

What is the Go equivalent of PHP’s ‘implode‘?

How to solve:

In the standard library: strings.Join

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

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

Cheers!

Answer:

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, ", "))

Answer:

s := []string{"this", "is", "a", "joined", "string\n"};
strings.Join(s, " ");

Did this help you?

Answer:

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)
}

Leave a Reply

Your email address will not be published. Required fields are marked *