Как напечатать Slice с разделенными запятыми значениями в golang - PullRequest
0 голосов
/ 29 апреля 2020

ВХОД:

    // a slice of type string.
    data := []string{"one", "two", "three"}

Ожидаемый вывод:

["one","two","three"]

Я пытался использовать эти спецификаторы формата https://play.golang.org/p/zBcFAh7YoVn

fmt.Printf("%+q\n", data)
fmt.Printf("%#q\n", data)
fmt.Printf("%q\n", data)
// using strings.Join()
result := strings.Join(data, ",")
fmt.Println(result)

Вывод: Все значения без запятой,

["one" "two" "three"]
[`one` `two` `three`]
["one" "two" "three"]
one,two,three

1 Ответ

0 голосов
/ 30 апреля 2020

Не знаю, это поможет, но я просто добавляю свои мысли !!

package main

import "fmt"

func main() {

    data := []string{"one", "two", "three"}
    //fmt.Println(data)
    for index, j := range data {
        if index == 0 { //If the value is first one 
            fmt.Printf("[ '%v', ", j)
        } else if len(data) == index+1 { // If the value is the last one 
            fmt.Printf("'%v' ]", j)
        } else {
            fmt.Printf(" '%v', ", j)   // for all ( middle ) values 
        }

    }
}

OutPut

[ 'one',  'two', 'three' ]

PlayGroundLink

...