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
+9.8k Golang : Check a web page existence with HEAD request example
+20.4k Golang : Convert PNG transparent background image to JPG or JPEG image
+31k Golang : Get local IP and MAC address
+12.1k Golang : Extract part of string with regular expression
+9.3k Golang : Validate IPv6 example
+4.5k Which content-type(MIME type) to use for JSON data
+8.5k Golang : Accept any number of function arguments with three dots(...)
+21.9k Golang : Repeat a character by multiple of x factor
+12k Golang : Get month name from date example
+39.5k Golang : Convert to io.ReadSeeker type
+12.2k Golang : HTTP response JSON encoded data
+9.8k Golang : Detect number of faces or vehicles in a photo