Golang : Populate or initialize struct with values example
A quick and short example on how to populate or initialize a struct with values. Pretty straight forward, but it could be confusing for those new to Golang or programming in general.
Here you go!
package main
import (
"fmt"
)
func main() {
myFirstStruct := struct {
Name string
Age int
}{
Name: "Caleb",
Age: 102,
} // populate with value
mySecondStruct := struct {
Name string
Age int
}{}
// empty or un-initialize. Golang will populate them automatically with default value
// such as empty string or zero
fmt.Printf("myFirstStruct struct : %+v\n", myFirstStruct)
fmt.Printf("mySecondStruct struct : %+v\n", mySecondStruct)
}
Output :
myFirstStruct struct : {Name:Caleb Age:102}
mySecondStruct struct : {Name: Age:0}
Play at : http://play.golang.org/p/f4TUFKs5pK
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
+14.4k Golang : Find commonalities in two slices or arrays example
+7k Golang : Check if one string(rune) is permutation of another string(rune)
+12.1k Elastic Search : Return all records (higher than default 10)
+17k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+5.7k AWS S3 : Prevent Hotlinking policy
+11.2k Golang : Generate DSA private, public key and PEM files example
+18.4k Golang : convert int to string
+12k Golang : Print UTF-8 fonts on image example
+14.1k Golang : How to filter a map's elements for faster lookup
+6.6k Swift : substringWithRange() function example
+6.7k Golang : How to setup a disk space used monitoring service with Telegram bot
+8.8k Golang : Intercept and compare HTTP response code example