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.2k Golang : Join lines with certain suffix symbol example
+11k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+5.5k Golang : How to validate ISBN?
+17.1k Golang : Implement getters and setters
+4.2k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+10.7k Golang : Perform sanity checks on filename example
+6.8k Javascript : Put image into Chrome browser's console
+14.9k Golang : convert string or integer to big.Int type
+20.1k Golang : Convert(cast) string to rune and back to string example
+5.5k Golang : Calculate diameter, circumference, area, sphere surface and volume
+26.8k Golang : Connect to database (MySQL/MariaDB) server
+9.3k Golang : How to delete element(data) from map ?