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
+6.8k Golang : How to determine if request or crawl is from Google robots
+8.9k Yum Error: no such table: packages
+7k Mac/Linux/Windows : Get CPU information from command line
+5.2k Golang : Check if a word is countable or not
+22.5k Golang : Convert seconds to minutes and remainder seconds
+3.7k Java : Get FX sentiment from website example
+17.6k Golang : Multi threading or run two processes or more example
+9.6k Mac OSX : Get a process/daemon status information
+14.7k Golang : Execute function at intervals or after some delay
+14.1k Golang : How to determine if a year is leap year?
+9.8k Golang : Eroding and dilating image with OpenCV example