I want a function func format(s []string) string
such that for two string slices s1
and s2
, if reflect.DeepEqual(s1, s2) == false
, then format(s1) != format(s2)
.
If I simply use fmt.Sprint
, slices ["a", "b", "c"]
and ["a b", "c"]
are all printed as [a b c]
, which is undesirable; and there is also the problem of string([]byte('4', 0, '2'))
having the same representation as "42"
.
Use a format verb that shows the data structure, like %#v
. In this case %q
works well too because the primitive types are all strings.
fmt.Printf("%#v
", []string{"a", "b", "c"})
fmt.Printf("%#v
", []string{"a b", "c"})
// prints
// []string{"a", "b", "c"}
// []string{"a b", "c"}
You may use:
func format(s1, s2 []string) string {
if reflect.DeepEqual(s1, s2) {
return "%v
"
}
return "%q
"
}
Like this working sample (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
"
}
return "%q
"
}
output:
["a" "b" "c"]
["a b" "c"]
[a b c]
[a b c]