Go string interpolation
Asked Answered
O

4

28

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 ?

Ormandy answered 30/4, 2018 at 7:13 Comment(0)
F
41

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))
Fraase answered 30/4, 2018 at 7:18 Comment(0)
G
7

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))
Gissing answered 30/4, 2018 at 7:19 Comment(0)
S
1

fmt.Sprintln returns the expanded first argument.

Smectic answered 30/4, 2018 at 7:18 Comment(0)
F
0

It might be useful. In case you have a long/multi line string with quotes and don't want to play with scape here is a good way to do it:

descriptionTemplate:= `{"name":"%s","surname":"%s","address":"%s","age":"%d"}`
    
newString := fmt.Sprintf(descriptionTemplate, name, surname, address, age)
Fright answered 11/7 at 14:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.