snippetgoCritical
Format a Go string without printing?
Viewed 0 times
stringformatprintingwithout
Problem
Is there a simple way to format a string in Go without printing the string?
I can do:
But I want the formatted string returned rather than printed so I can manipulate it further.
I could also do something like:
But this becomes difficult to read when the format string is complex, and cumbersome when one or many of the parts aren't strings and have to be converted first, like
Is there a simpler way to do this?
I can do:
bar := "bar"
fmt.Printf("foo: %s", bar)But I want the formatted string returned rather than printed so I can manipulate it further.
I could also do something like:
s := "foo: " + barBut this becomes difficult to read when the format string is complex, and cumbersome when one or many of the parts aren't strings and have to be converted first, like
i := 25
s := "foo: " + strconv.Itoa(i)Is there a simpler way to do this?
Solution
Sprintf is what you are looking for.
Example
You can also see it in use in the Errors example as part of "A Tour of Go."
Example
fmt.Sprintf("foo: %s", bar)You can also see it in use in the Errors example as part of "A Tour of Go."
return fmt.Sprintf("at %v, %s", e.When, e.What)Code Snippets
fmt.Sprintf("foo: %s", bar)return fmt.Sprintf("at %v, %s", e.When, e.What)Context
Stack Overflow Q#11123865, score: 735
Revisions (0)
No revisions yet.