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
+7.7k Golang : Dealing with struct's private part
+22.5k Golang : Read directory content with filepath.Walk()
+8.4k Golang : Emulate NumPy way of creating matrix example
+7.5k Golang : Individual and total number of words counter example
+5.5k Golang : Get S3 or CloudFront object or file information
+9.1k Golang : Go as a script or running go with shebang/hashbang style
+4k Golang : Switch Redis database redis.NewClient
+9.4k Golang : Generate Codabar
+9k Golang : Sort lines of text example
+5.8k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+8.5k Golang : Configure Apache and NGINX to access your Go service example
+31k error: trying to remove "yum", which is protected