2

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".

2 Answers 2

9

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\n", []string{"a", "b", "c"})
fmt.Printf("%#v\n", []string{"a b", "c"})

// prints
// []string{"a", "b", "c"}
// []string{"a b", "c"}
Sign up to request clarification or add additional context in comments.

1 Comment

Ha, that's a very good solution — I should have read golang.org/pkg/fmt more closely. Thanks!
1

You may use:

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

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\n"
    }
    return "%q\n"
}

output:

["a" "b" "c"]
["a b" "c"]
[a b c]
[a b c]

1 Comment

Your answers are way too long and (perhaps unnecessarily) illustrative even when the question requires a short answer with perhaps 1-2 lines of code. I up voted nevertheless to convey no offence as I've learned quite a bit from your other answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.