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
+5.1k Golang : Extract XML attribute data with attr field tag example
+7.9k Golang : How to use Gorilla webtoolkit context package properly
+29.6k error: trying to remove "yum", which is protected
+10k Golang : How to pipe input data to executing child process?
+13.2k Golang : Overwrite previous output with count down timer
+7.4k PHP : How to parse ElasticSearch JSON ?
+3.9k Which content-type(MIME type) to use for JSON data
+11.6k Golang : Pass database connection to function called from another package and HTTP Handler
+5.8k Fix sudo yum hang problem with no output or error messages
+10.6k Golang : Convert decimal number(integer) to IPv4 address
+9.6k Golang : Fix go.exe is not compatible with the version of Windows you're running
+4.4k Golang : Generate Interleaved 2 inch by 5 inch barcode