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
+3.9k Mac OSX : Get disk partitions' size, type and name
+12.6k Golang : Get dimension(width and height) of image file
+15.7k Golang : read gzipped http response
+11k Golang : Convert decimal number(integer) to IPv4 address
+10.7k SSL : The certificate is not trusted because no issuer chain was provided
+5.1k Golang : Denco multiplexer example
+4.5k Golang : Issue HTTP commands to server and port example
+20.2k Golang : How to read float value from standard input ?
+6.2k Golang : Get environment variable
+18.6k Golang : Close channel after ticker stopped example
+7k Golang : Get today's weekday name and calculate target day distance example
+12.3k Facebook PHP getUser() returns 0