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
+5.4k Grep : How to grep for strings inside binary data
+12.7k Android Studio : Use image as AlertDialog title with custom layout example
+7.2k Your page has meta tags in the body instead of the head
+18.2k Golang : Delete item from slice based on index/key position
+3.8k Golang : Experimental Jawi programming language
+4.6k PHP : Convert CSV to JSON with YQL example
+7k Findstr command the Grep equivalent for Windows
+10.8k Golang : Save webcamera frames to video file
+20.6k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+5.7k Golang : Output or print out JSON stream/encoded data
+9.1k Golang : Resolve domain name to IP4 and IP6 addresses.
+4.4k Unix/Linux : How to archive and compress entire directory ?