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
+7.7k Android Studio : AlertDialog to get user attention example
+7.2k Restart Apache or Nginx web server without password prompt
+22.3k Golang : Securing password with salt
+12.4k Golang : Get month name from date example
+12.9k Golang : Convert int(year) to time.Time type
+6.7k Golang : Embedded or data bundling example
+5.5k Golang : If else example and common mistake
+6.1k Golang : Function as an argument type example
+19.4k Golang : Get host name or domain name from IP address
+12.7k Golang : Transform comma separated string to slice example
+6.4k Golang : How to search a list of records or data structures