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
+17.1k Golang : Covert map/slice/array to JSON or XML format
+12.3k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+6.5k Golang : Handling image beyond OpenCV video capture boundary
+6.6k Golang : Spell checking with ispell example
+4.8k Unix/Linux : How to pipe/save output of a command to file?
+5.4k Python : Delay with time.sleep() function example
+12.5k Golang : HTTP response JSON encoded data
+23k Golang : Calculate time different
+9.7k Golang : Eroding and dilating image with OpenCV example
+30.9k Golang : Interpolating or substituting variables in string examples
+4.8k Golang : How to pass data between controllers with JSON Web Token
+32.2k Golang : Convert []string to []byte examples