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
+7.5k Golang : Test if an input is an Armstrong number example
+10.1k Golang : Wait and sync.WaitGroup example
+4.7k Google : Block or disable caching of your website content
+9.8k Golang : Edge detection with Sobel method
+7.7k Golang Hello World Example
+9.8k Golang : Channels and buffered channels examples
+9.1k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+21.8k Golang : Convert seconds to minutes and remainder seconds
+16.6k Golang : Get own process identifier
+7.3k Golang : Shuffle strings array
+5.1k Golang : Pad file extension automagically
+10.7k Golang : Replace a parameter's value inside a configuration file example