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
+10.3k Golang : Convert file content to Hex
+8.1k Golang : Append and add item in slice
+9.5k Golang : Get all countries currencies code in JSON format
+22.1k Golang : Join arrays or slices example
+5.1k Linux : How to set root password in Linux Mint
+10.2k Golang : Find and replace data in all files recursively
+5.9k Golang : Detect variable or constant type
+5k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+17.5k Golang : Find smallest number in array
+12.1k Golang : convert(cast) string to integer value
+25.9k Golang : How to read integer value from standard input ?
+12.2k Golang : Split strings into command line arguments