Golang : Print out struct values in string format
This tutorial will show you how to create a method for a struct
to print out the struct
values out in string. The source code below should be self explanatory.
package main
import (
"strconv"
"fmt"
)
type Person struct {
Title string
Surname string
Age int
}
// method for type Person
func (this Person) String() string {
return this.Title + " " + this.Surname + " " + strconv.Itoa(this.Age) // convert int to string
}
func main() {
var guy Person
guy.Title = "Mr."
guy.Surname = "Smith"
guy.Age = 12
// print values
fmt.Println(guy.Title, guy.Surname, guy.Age)
// or use method
fmt.Println(guy.String())
}
Output :
Mr. Smith 12
Mr. Smith 12
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
+11k Golang : Exit, terminating or aborting a program
+3.6k Linux/MacOSX : How to symlink a file?
+24.4k Golang : dial tcp: too many colons in address
+5.5k PHP : Shuffle to display different content or advertisement
+2.4k Java : Get FX sentiment from website example
+10k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+6.1k Javascript : Push notifications to browser with Push.js
+17.8k Golang : Archive directory with tar and gzip
+5.2k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+14.8k Golang : read gzipped http response
+7k Android Studio : Indicate progression with ProgressBar example
+52.3k Golang : Unmarshal JSON from http response