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
+20.4k Golang : Saving private and public key to files
+5.5k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+11.4k Golang : Calculations using complex numbers example
+7.1k Linux : How to fix Brother HL-1110 printing blank page problem
+11.6k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+22.7k Golang : Randomly pick an item from a slice/array example
+12.3k Golang : Transform comma separated string to slice example
+34.7k Golang : Upload and download file to/from AWS S3
+8.4k Golang : Set or add headers for many or different handlers
+86k Golang : How to convert character to ASCII and back
+5.5k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error