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
+6.7k Golang : When to use make or new?
+43.7k Golang : Get hardware information such as disk, memory and CPU usage
+4.7k Mac OSX : Get disk partitions' size, type and name
+9.5k Mac OSX : Get a process/daemon status information
+4.9k HTTP common errors and their meaning explained
+23.7k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+13.5k Golang : Increment string example
+18.3k Golang : Put UTF8 text on OpenCV video capture image frame
+7.3k Golang : alternative to os.Exit() function
+7k Fix sudo yum hang problem with no output or error messages
+20.8k Golang : Read directory content with os.Open
+6k Linux/MacOSX : Search for files by filename and extension with find command