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
+16.2k Golang : Multi threading or run two processes or more example
+20.6k Golang : Use TLS version 1.2 and enforce server security configuration over client
+19.1k Golang : Secure(TLS) connection between server and client
+13.8k Golang : Get HTTP protocol version example
+7.7k Golang : Set or add headers for many or different handlers
+5.2k Golang : Scan forex opportunities by Bollinger bands
+6.1k Golang : Fibonacci number generator examples
+19.8k Curl usage examples with Golang
+7.4k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+13.8k Golang : How to check for empty array string or string?
+8k Golang : What is the default port number for connecting to MySQL/MariaDB database ?