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
+5k Which content-type(MIME type) to use for JSON data
+7.9k Golang : Scan files for certain pattern and rename part of the files
+24.3k Golang : Upload to S3 with official aws-sdk-go package
+22.1k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+39.9k Golang : Remove dashes(or any character) from string
+25.3k Golang : Create PDF file from HTML file
+5.5k Python : Delay with time.sleep() function example
+21.6k Golang : How to force compile or remove object files first before rebuild?
+9k Golang : On lambda, anonymous, inline functions and function literals
+8.5k Golang: Prevent over writing file with md5 hash
+23.1k Golang : Calculate time different