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
+5.1k Golang : How to display image file or expose CSS, JS files from localhost?
+3.1k Android Studio : Image button and button example
+7.7k CodeIgniter : How to check if a session exist in PHP?
+3.7k Golang : Concatenate (combine) buffer data example
+10.2k Golang : GORM create record or insert new record into database example
+3.7k Golang : Of hash table and hash map
+2.6k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+3.2k Golang : Quadratic example
+14k Golang : Calculate time different
+5.1k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+3.4k Golang : Randomize letters from a string example
+1.7k Nginx and PageSpeed build from source CentOS example