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
+22.1k Golang : Securing password with salt
+15.1k Golang : Get timezone offset from date or timestamp
+15k Golang : Save(pipe) HTTP response into a file
+7k Golang : Squaring elements in array
+5k Golang : PGX CopyFrom to insert rows into Postgres database
+30.7k error: trying to remove "yum", which is protected
+11k Golang : Simple image viewer with Go-GTK
+8.9k Golang : Capture text return from exec function example
+15.2k Golang : How to get Unix file descriptor for console and file
+5.9k PHP : Get client IP address
+7.8k Golang : Gomobile init produce "iphoneos" cannot be located error
+15.8k Golang : Read a file line by line