-3

I need to create a string with html link inside.

fmt.Sprint("<a href=\"%s\">%s</a>", "/myUrl", "link text");

Expected result is

<a href="/myUrl">link text</a>

But real result is

<a href="%s">%s</a>/myUrllink text

What am I doing wrong?

By the way, I have this warning in GoLand

enter image description here

Flimzy
  • 60,850
  • 13
  • 104
  • 147
Vitalii
  • 7,565
  • 13
  • 53
  • 114
  • 5
    you forgot the `f`. – tkausl Nov 30 '17 at 10:06
  • Related with more details: [Golang: format a string without printing?](https://stackoverflow.com/questions/11123865/golang-format-a-string-without-printing/31742265#31742265) – icza Nov 30 '17 at 12:30
  • 1
    Looks like a job for [go vet](https://golang.org/cmd/vet/#hdr-Printf_family). It'll warn you about things like these. Very common :) – k1m190r Nov 30 '17 at 13:03

2 Answers2

7

fmt.Sprint will print the string as it is. If you want to format the string, you should use fmt.Sprintf.


The SO community can be very harsh on beginners, if people do not like what you have written or how you worded the question you will get down voted. Don't fool yourself thinking people are here to help, they only care for the reputation.

Luckily in Go we have pretty good docs. If you ever think something is not working properly, chances are that a glance at the docs website will be enough to get you going.

Eduardo Braun
  • 111
  • 1
  • 5
1

func Sprintf

func Sprintf(format string, a ...interface{}) string

Sprintf formats according to a format specifier and returns the resulting string.

func Sprint

func Sprint(a ...interface{}) string

Sprint formats using the default formats for its operands and returns the resulting string. Spaces are added between operands when neither is a string.


Also fmt is pretty big and very useful standard package with a good documentation. You can find a lot of different I/O functions there.

Also it is perkily and weird to write "incorrect result" if you hasn't read a documentation.

I159
  • 24,762
  • 27
  • 88
  • 124