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 : How to stop user from directly running an executable file?
+10.5k Golang : cannot assign type int to value (type uint8) in range error
+14.6k Golang : Rename directory
+11.4k Golang : Fix - does not implement sort.Interface (missing Len method)
+19.7k Golang : Close channel after ticker stopped example
+6.2k Golang : Create new color from command line parameters
+7.4k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+9.4k Golang : Generate random Chinese, Japanese, Korean and other runes
+19.9k Golang : Archive directory with tar and gzip
+7k Golang : Pat multiplexer routing example
+24.7k Golang : How to validate URL the right way
+26.1k Golang : How to read integer value from standard input ?