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
+4.9k Golang : List all packages and search for certain package
+12.8k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+5k Golang : Calculate US Dollar Index (DXY)
+10.8k Golang : Pagination with go-paginator configuration example
+12.1k Golang : error parsing regexp: invalid or unsupported Perl syntax
+13.3k Golang : How to filter a map's elements for faster lookup
+9.6k Golang : Command line file upload program to server example
+6.1k Nginx : How to block user agent ?
+9.4k Golang : Flip coin example
+3.9k Golang : A program that contain another program and executes it during run-time
+32.7k Golang : convert(cast) bytes to string
+18.5k Golang : How to get time from unix nano example