-1

The following works in tests:

if actualKey != expectedKey {
    t.Fatalf("Failed. Actual: %q. Expected: %q", actualKey, expectedKey)
}

In the main code:

m["Keyword "+kw+" found on "+url] = 0

, but this fails:

m["Keyword %q found on %q", kw, url] = 0

As suggested by @JimB fmt.Sprintf could be used. The following works:

msg := fmt.Sprintf("Keyword %q found on %q", kw, url)
m[msg] = 0

Questions

  • Is it correct to call this approach variable referencing? If false, what is it called?
  • Is this the most concise way of implementing it?
030
  • 10,842
  • 12
  • 78
  • 123
  • 2
    Are you just looking for string formatting? [`fmt.Sprintf`](https://golang.org/pkg/fmt/#Sprintf)? – JimB Jul 21 '16 at 13:06
  • @JimB Thank you. It works. I have updated the questions. Could you post an answer and answer the additional questions? – 030 Jul 21 '16 at 13:15
  • Possible duplicate: http://stackoverflow.com/questions/11123865/golang-format-a-string-without-printing. What is string formatting called? -- "Formatting"? (that's what the `f` on the end of `Fatalf`, `Printf`, `Sprintf` signifies). What do you mean the most concise way to implement it? Are you trying to write your own formatter? – JimB Jul 21 '16 at 13:28
  • @JimB No. I do not want to reinvent the wheel. `msg := fmt.Sprintf("Keyword %q found on %q", kw, url)` – 030 Jul 21 '16 at 13:31
  • @JimB calling variables in a String is just called String Formatting? "hello" + var is called the same as fmt.Sprintf("hello %q", var)? – 030 Jul 21 '16 at 13:34
  • `"hello " + var` only works with 2 strings, hence it's simple concatenation. String formatting "formats" the variables in different ways depending on the verb being used., for example you used `%q`, which adds quotes around strings. That's not really the same as concatenating two strings. – JimB Jul 21 '16 at 13:37
  • @JimB I agree with that. I was wondering whether there is a name for the latter. `String concatenation` vs. `?` – 030 Jul 21 '16 at 13:50

1 Answers1

0

I think a better way to do it is by defining a struct type:

type Result struct {
    Keyword, URL string
}

and use it like this:

m := make(map[Result]int)
m[{"keyword1", "url1"}] = 0
seriousdev
  • 7,519
  • 8
  • 45
  • 52