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
+5.8k Golang : How to verify input is rune?
+6.6k Android Studio : Hello World example
+6.3k Unix/Linux : How to get own IP address ?
+52k Golang : How to get struct field and value by name
+8.6k Golang : Accept any number of function arguments with three dots(...)
+19.8k Golang : Convert seconds to human readable time format example
+9.2k Golang : Extract or copy items from map based on value
+16.5k Golang : Set up source IP address before making HTTP request
+7.3k Golang : How to handle file size larger than available memory panic issue
+19.1k Golang : Fix cannot download, $GOPATH not set error
+9.8k Golang : Identifying Golang HTTP client request