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
+4k Javascript : Empty an array example
+10.2k Golang : Embed secret text string into binary(executable) file
+5k Golang : Check if a word is countable or not
+7.9k Golang : What fmt.Println() can do and println() cannot do
+20k Golang : Compare floating-point numbers
+8.4k Golang : Another camera capture GUI application with GTK and OpenCV
+18.3k Golang : How to get hour, minute, second from time?
+13.7k Golang : unknown escape sequence error
+13.8k Golang : convert rune to unicode hexadecimal value and back to rune character
+21.4k Golang : Encrypt and decrypt data with TripleDES
+22k Golang : Convert seconds to minutes and remainder seconds
+14.2k Golang : How to pass map to html template and access the map's elements