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
+10.5k Android Studio : Simple input textbox and intercept key example
+6.9k Golang : Fibonacci number generator examples
+24.9k Golang : Create PDF file from HTML file
+13.9k Golang : Compress and decompress file with compress/flate example
+6.1k Golang : Extract XML attribute data with attr field tag example
+19.1k Mac OSX : Homebrew and Golang
+13.1k Golang : Convert(cast) int to int64
+11.3k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+26k Mac/Linux and Golang : Fix bind: address already in use error
+6.2k Golang & Javascript : How to save cropped image to file on server
+14.5k Golang : Overwrite previous output with count down timer