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
+5.7k Golang : Muxing with Martini example
+4.2k Golang : Pad file extension automagically
+5.2k Golang : Process non-XML/JSON formatted ASCII text file example
+9.8k Golang : Natural string sorting example
+5.2k Golang : Experimental emojis or emoticons icons programming language
+3.1k Detect if Google Analytics and Developer Media are loaded properly or not
+18k Golang : How to run your code only once with sync.Once object
+15.3k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+8.1k Golang : Detect number of active displays and the display's resolution
+4.2k Golang : Get FX sentiment from website example
+4.9k Golang : Generate multiplication table from an integer example
+22.8k Golang : How to validate URL the right way