Go String Interpolation

Go String Interpolation

Trying to interpolate an int value into a string using %v formatter as follows, yet nothing is printed,

package main

import "fmt"

func inc(i int) int {
  return i + 1
}

func main() {
  fmt.Sprintln("inc 1 equal %v", inc(1))
}

How to interpolate an int value ?

3 Answers

fmt.Sprintln returns a String, but doesn't print anything. (The name was taken from the also confusingly named C function sprintf.)

What you need is Printf, but you have to add the newline yourself:

fmt.Printf("inc 1 equal %v\n", inc(1))
0

Sprintln formats using the default formats for its operands and returns the resulting string. Spaces are always added between operands and a newline is appended.

Sprint format a string and returns such a string, it does write nothing. What you're searching for is Print

Furthermore, the variant ln doesn't parse %, it only add the new line character at the end of the string.

So, if you want to write to standard output using format, you should use this:

fmt.Printf("inc 1 equal %v", inc(1))

fmt.Sprintln returns the expanded first argument.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.