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
+11.4k Golang : Exit, terminating or aborting a program
+11.7k Golang : Convert(cast) uintptr to string example
+12.1k Swift : Convert (cast) Int to String ?
+4.8k List of Golang XML tutorials
+6.8k Swift : Convert (cast) String to Double
+13.5k Golang : Execute function at intervals or after some delay
+6.7k Golang : How to execute code at certain day, hour and minute?
+6.3k Golang : Dealing with postal or zip code example
+6k Golang : How to iterate a slice without using for loop?
+7.6k Golang : Executing and evaluating nested loop in html template
+8.5k Golang : Copy map(hash table) example
+6.3k Golang : Word limiter example