Created
February 23, 2023 17:40
-
-
Save knaveightt/ddcf3370a47f2c7cbd108fc8fb2d4562 to your computer and use it in GitHub Desktop.
Learn Go - Maps and Structs examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Map examples, Struct examples | |
package main | |
import ( | |
"fmt" | |
"reflect" | |
) | |
// used for checking tags | |
type Doctor struct { | |
number int | |
Name string // Doctor.Name is visible outside the package | |
companions []string | |
} | |
type Surgeon struct { | |
Doctor | |
tools string `required max:"100"` // tagged for ensuring this does not exceed a max of 100 | |
} | |
func main() { | |
statePopulations := map[string]int{ | |
"California": 39393, | |
"Pennsynvania": 45454, | |
"New Jersey": 11223, | |
} | |
fmt.Println(statePopulations) | |
fmt.Println(statePopulations["California"]) | |
// can use make to make an empty map | |
newMap := make(map[string]int) | |
newMap["newKey"] = 888 | |
fmt.Println(newMap["newKey"]) | |
// Note: return order of maps is random, vs a slice or array which maintains order | |
// You can also delete a key | |
delete(newMap, "newKey") | |
check, ok := newMap["newKey"] // if a key does not exist, it will automatically return 0, and set the 'ok' var | |
fmt.Println(check, ok) | |
// copying maps share the same object | |
sp := statePopulations | |
delete(sp, "New Jersey") | |
fmt.Println(statePopulations) | |
fmt.Println(sp) | |
// using a struct | |
aDoctor := Doctor{ | |
number: 3, | |
Name: "John", | |
companions: []string{ | |
"PersonA", | |
"PersonB", | |
"PersonC", | |
}, | |
} | |
fmt.Println(aDoctor) | |
fmt.Println(aDoctor.Name) | |
fmt.Println(aDoctor.companions[2]) | |
// anonymous structure | |
newDoc := struct{ name string }{name: "My Name"} | |
fmt.Println(newDoc) | |
// Go supports composition via embedding - VERSUS TRADITIONAL OOP / CLASS INHERITANCE | |
// Note, Surgeon IS NOT a Doctor, it HAS a Doctor component but it is not the same | |
// While methods can carry through in this way, generally it is better to leverage interfaces for this | |
aSurgeon := Surgeon{} | |
aSurgeon.number = 10 | |
aSurgeon.Name = "Toby" | |
aSurgeon.companions = []string{"Tom", "John"} | |
aSurgeon.tools = "Slicer" | |
fmt.Println(aSurgeon) | |
// Access the struct tag | |
t := reflect.TypeOf(Surgeon{}) | |
field, _ := t.FieldByName("tools") | |
fmt.Println(field.Tag) // you can parse this value to test the actual value of this member | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment