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
+30k Golang : Math pow(the power of x^y) example
+10.3k Golang : Byte format example
+7.6k Golang : Gorilla web tool kit schema example
+8.9k Golang : Print how to use flag for your application example
+45.3k Golang : Convert int to byte array([]byte)
+3.9k MariaDB/MySQL : Form select statement or search query with Chinese characters
+15.5k Golang : Capture stdout of a child process and act according to the result
+4.7k Javascript : How to refresh page with JQuery ?
+7.1k Golang : HTTP Server Example
+16k Golang : How to remove certain lines from a file
+37.7k Golang : Remove dashes(or any character) from string
+19.5k Golang : How to read float value from standard input ?