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
+38.8k Golang : How to read CSV file
+11.8k Golang : Perform sanity checks on filename example
+9k Golang : How to get garbage collection data?
+11.7k Golang : Detect user location with HTML5 geo-location
+16.1k CodeIgniter/PHP : Create directory if does not exist example
+5.9k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+13.6k Golang : convert rune to unicode hexadecimal value and back to rune character
+11.7k Golang : Convert a rune to unicode style string \u
+9.3k Golang : Validate IPv6 example
+77.6k Golang : How to return HTTP status code?
+7.4k Golang : Error reading timestamp with GORM or SQL driver
+20.3k Golang : Read directory content with os.Open