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
+8.1k Golang : cannot assign type int to value (type uint8) in range error
+14.8k Golang : How to log each HTTP request to your web server?
+11.7k Golang : Strings comparison
+8.7k Golang : How to use if, eq and print properly in html template
+4.1k Java : Human readable password generator
+6.3k Swift : Convert (cast) String to Double
+9.1k Golang : Secure file deletion with wipe example
+28.2k Golang : Download file example
+16k Golang : Convert seconds to human readable time format example
+13.7k Golang : Set up source IP address before making HTTP request
+10k Golang : Handle API query by curl with Gorilla Queries example
+10.1k Swift : Convert (cast) Int or int32 value to CGFloat