Golang : Interpolating or substituting variables in string examples
For this quick tutorial, we will explore how to interpolate(substitute) actual data into variables inside a string. Will keep these examples as simple as possible and once you are comfortable, do explore the advanced example at https://www.socketloop.com/tutorials/golang-auto-generate-reply-email-with-text-template-package
Example 1:
package main
import (
"fmt"
)
func main() {
msg := "%s has %d messages."
name := "Steve"
num := 50
result := fmt.Sprintf(msg, name, num)
fmt.Println(result)
}
Output:
Steve has 50 messages.
To substitute more variables ( higher than 3), it is recommended to use the text/template
package.
Example 2:
package main
import (
"fmt"
"os"
"text/template"
)
type Data struct {
Name string // has to be uppercase/exportable/public
Num uint // for the interpolation/substitution to work
}
func main() {
msg := "{{.Name}} has {{.Num}} messages.\n"
substitute := Data{"Steve", 50}
tmpl, err := template.New("msg").Parse(msg)
err = tmpl.Execute(os.Stdout, substitute)
if err != nil {
fmt.Println(err)
}
}
Output:
Steve has 50 messages.
References:
https://www.socketloop.com/tutorials/golang-auto-generate-reply-email-with-text-template-package
https://golang.org/pkg/text/template/
https://www.socketloop.com/tutorials/golang-find-replace-character-in-string
See also : Golang : Auto-generate reply email with text/template package
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.7k Python : Convert IPv6 address to decimal and back to IPv6
+10.1k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+9.4k Golang : Underscore string example
+15.7k Golang : How to tell if a file is compressed either gzip or zip ?
+4.4k Unix/Linux : How to archive and compress entire directory ?
+7.4k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+5.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+5.9k Golang : Decode XML data from RSS feed
+28.6k Golang : How to get HTTP request header information?
+7k Golang : Get final or effective URL with Request.URL example
+14.5k Golang : Read large file with bufio.Scanner cause token too long error
+8.4k Golang : ffmpeg with os/exec.Command() returns non-zero status