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
+16.9k Golang : How to read float value from standard input ?
+9k How to tell if a binary(executable) file or web application is built with Golang?
+4.3k Golang : Struct field tags and what is their purpose?
+7.5k Golang : Load ASN1 encoded DSA public key PEM file example
+10.2k Golang : Pass database connection to function called from another package and HTTP Handler
+10.3k Golang : Extract part of string with regular expression
+8.3k Golang : Convert file unix timestamp to UTC time example
+8k Golang : Channels and buffered channels examples
+8.5k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+14.4k Golang : Get number of CPU cores
+6k Golang : Tell color name with OpenCV example
+11.2k Golang : How to login and logout with JWT example