Search code examples
gomultidimensional-arraygoroutine

Need to convert 2 Dimensional array into string and replace the last comma with full stop.(Golang)


How can I create string out of multi-dimensional array, preferably using goroutine or channel, in order to replace the last comma of the element with a full-stop?

Thanks

package main

import (
    "fmt"
)

func main() {
    pls := [][]string {
       {"C", "C++"},
       {"JavaScript"},
       {"Go", "Rust"},
    }
    for _, v1 := range pls {
        for _, v2 := range v1 {
            fmt.Print(v2,", ")
        }
    }
}

Solution

  • I guess classic strings.Join would be easier to implement and maintain:

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        pls := [][]string{
            {"C", "C++"},
            {"JavaScript"},
            {"Go", "Rust"},
        }
    
        var strs []string
    
        for _, v1 := range pls {
            s := strings.Join(v1, ", ")
            strs = append(strs, s)
    
        }
        s := strings.Join(strs, ", ")
        fmt.Println(s)
    }
    

    https://play.golang.org/p/2Nuv00PV5j