Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 469
elm Avatar asked Apr 30 '18 07:04

elm


2 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))
like image 174
Thomas Avatar answered Sep 19 '22 01:09

Thomas


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))
like image 40
Ivan Beldad Avatar answered Sep 21 '22 01:09

Ivan Beldad