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
+13.5k Golang : Save(pipe) HTTP response into a file
+22.3k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+8.7k Golang : Turn string or text file into slice example
+8.3k Golang : Read file with ioutil
+11.7k Golang : Convert int(year) to time.Time type
+10.1k Golang : Concatenate (combine) buffer data example
+5.7k Golang : How to setup a disk space used monitoring service with Telegram bot
+18.3k Golang : Measure http.Get() execution time
+23k Golang : Daemonizing a simple web server process example
+19.9k Golang : Sort and reverse sort a slice of strings
+5.1k Golang : Detect variable or constant type
+32.4k Golang : Converting a negative number to positive number