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
+14k Golang : unknown escape sequence error
+15.7k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+8.9k Yum Error: no such table: packages
+26.8k Golang : How to check if a connection to database is still alive ?
+5.5k Golang : Return multiple values from function
+13.3k Golang : Convert(cast) int to int64
+10.7k Golang : Select region of interest with mouse click and crop from image
+8k Golang : Gomobile init produce "iphoneos" cannot be located error
+20.5k Golang : How to get own program name during runtime ?
+17.8k Convert JSON to CSV in Golang
+7.7k Golang : Dealing with struct's private part