How to use map of structs in Golang 1.20

Channel:
Subscribers:
5,740
Published on ● Video Link: https://www.youtube.com/watch?v=gAM_rkxAm_g



Category:
Tutorial
Duration: 2:19
0 views
0


In this video we are going to generate source code for the GoLang Program, How to use map of structs using chatGPT.
After generating we will verify and run the generated code.

IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.



##############SOURCE CODE#########################

package main

import "fmt"

type Person struct {
Name string
Age int
Address string
}

func main() {
// Declare a map of string keys and Person values
people := map[string]Person{
"John": {Name: "John", Age: 30, Address: "123 Main St"},
"Alice": {Name: "Alice", Age: 25, Address: "456 Oak St"},
}

// Print the map
fmt.Println("People:", people)

// Add a new person to the map
people["Bob"] = Person{Name: "Bob", Age: 35, Address: "789 Elm St"}

// Print the map again to show the new person was added
fmt.Println("People:", people)

// Iterate over the map using a for loop and print each person
for name, person := range people {
fmt.Printf("%s: %s (%d) lives at %s\n", name, person.Name, person.Age, person.Address)
}
}

##############END OF SOURCE CODE#########################

Below is the explanation for the program:


In this program, we define a Person struct with three fields: Name, Age, and Address.

We then declare a map of string keys and Person values using the syntax people := map[string]Person{key1: value1, key2: value2, ...}.
We initialize the map with two Person values using the struct literal syntax.

Next, we add a new Person to the map using the syntax people["Bob"] = Person{Name: "Bob", Age: 35, Address: "789 Elm St"}.

We then iterate over the map using a for loop and print each person's name, age, and address using fmt.Printf.

This output shows that the program has successfully demonstrated how to use a map of structs.
We declared a map of string keys and Person values, initialized it with two Person values, added a new Person to the map,
and then iterated over the map and printed each Person's name, age, and address.

#go #goprogramming #golang #golangtutorial #golanguage







Tags:
how to use map of structs in golang
go program to use map of structs
map and struct in go
struct inside map in go
go Programming Tutorial
go by example
go Language
go projects
go programming projects
go tutorial
golang tutorial
golang projects
go programming course
learn go
how to run go program
golang videos
golang with chatgpt
coding questions
coding interview questions