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.8k Golang : Create S3 bucket with official aws-sdk-go package
+7.6k Golang : Example of how to detect which type of script a word belongs to
+12.2k Golang : flag provided but not defined error
+32.2k Golang : Copy directory - including sub-directories and files
+5.6k Linux : Disable and enable IPv4 forwarding
+6.2k PHP : Proper way to get UTF-8 character or string length
+5.9k Golang : Measure execution time for a function
+6.5k Golang : When to use make or new?
+9.5k Golang : Load ASN1 encoded DSA public key PEM file example
+19.6k Golang : Count JSON objects and convert to slice/array
+13.9k Golang : Fix image: unknown format error
+6.4k Golang : Spell checking with ispell example