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
+21.9k Golang : Securing password with salt
+8.1k Golang : Implementing class(object-oriented programming style)
+3.5k Java : Random alphabets, alpha-numeric or numbers only string generator
+19.3k Golang : How to Set or Add Header http.ResponseWriter?
+15k Golang : Get HTTP protocol version example
+6.8k Golang : Gargish-English language translator
+50.6k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+19k Golang : Get RGBA values of each image pixel
+9.4k Golang : How to generate Code 39 barcode?
+8.6k Golang : Take screen shot of browser with JQuery example
+7.6k Golang : Example of how to detect which type of script a word belongs to
+19.5k Golang : Measure http.Get() execution time