Golang:以独特的方式打印字符串数组

时间:2016-08-25 15:55:59

标签: string go format slice

我想要一个函数func format(s []string) string,以便对于两个字符串切片s1s2,如果是reflect.DeepEqual(s1, s2) == false,那么format(s1) != format(s2)

如果我只使用fmt.Sprint,则切片["a", "b", "c"]["a b", "c"]都会打印为[a b c],这是不受欢迎的;并且还存在string([]byte('4', 0, '2'))"42"具有相同表示的问题。

2 个答案:

答案 0 :(得分:8)

使用显示数据结构的格式动词,例如%#v。在这种情况下,%q也可以正常工作,因为基本类型都是字符串。

fmt.Printf("%#v\n", []string{"a", "b", "c"})
fmt.Printf("%#v\n", []string{"a b", "c"})

// prints
// []string{"a", "b", "c"}
// []string{"a b", "c"}

答案 1 :(得分:1)

您可以使用:

func format(s1, s2 []string) string {
    if reflect.DeepEqual(s1, s2) {
        return "%v\n"
    }
    return "%q\n"
}

就像这个工作样本(The Go Playground):

package main

import (
    "fmt"
    "reflect"
)

func main() {
    s1, s2 := []string{"a", "b", "c"}, []string{"a b", "c"}
    frmat := format(s1, s2)
    fmt.Printf(frmat, s1) // ["a" "b" "c"]
    fmt.Printf(frmat, s2) // ["a b" "c"]

    s2 = []string{"a", "b", "c"}
    frmat = format(s1, s2)
    fmt.Printf(frmat, s1) // ["a" "b" "c"]
    fmt.Printf(frmat, s2) // ["a b" "c"]
}

func format(s1, s2 []string) string {
    if reflect.DeepEqual(s1, s2) {
        return "%v\n"
    }
    return "%q\n"
}

输出:

["a" "b" "c"]
["a b" "c"]
[a b c]
[a b c]
相关问题