Golang Maps - Getting Started with Golang

Опубликовано: 22 Февраль 2025
на канале: Maharlikans Code
97
7

In this Getting Started with Golang, we will learn how to use the Golang Maps map maps keys to values in Golang programming language with step by step guide.

#MaharlikansCode
#GolangMaps
#Golang
#LifeAsSoftwareDeveloper
#Maharlikans
#FilipinoSoftwareDeveloper

If you go with extra mile for buying me a cup of coffee, I appreciate it guys: https://ko-fi.com/maharlikanscode

Source Codes:
package main

import (
"fmt"
"time"
)

// UserSession stores the user's sessions into the Golang's Map
var UserSession = make(map[string]int64)

// StoreUserSession insert new user session to the map
func StoreUserSession(userName string) {
sessionExpiry := time.Now().Add(1 * time.Millisecond).Unix() // this serves as the user's session timeout
UserSession[userName] = sessionExpiry
}

func main() {
fmt.Println("Welcome to the Golang Maps!")

StoreUserSession("AAA")
time.Sleep(1 * time.Second)

StoreUserSession("BBB")
time.Sleep(1 * time.Second)

StoreUserSession("CCC")

// Loop through the map collections
for n, expDT := range UserSession {
fmt.Println("UserName: ", n, " expDT: ", expDT)
}

StoreUserSession("AAA")
time.Sleep(1 * time.Second)
fmt.Println("check duplicate key")

// Loop through the map collections
for n, expDT := range UserSession {
fmt.Println("UserName: ", n, " expDT: ", expDT)
}

// Delete the key from the Golang's Map
fmt.Println("delete the map's key here")
delete(UserSession, "AAA")

// Loop through the map collections
for n, expDT := range UserSession {
fmt.Println("UserName: ", n, " expDT: ", expDT)
}

usrSessionExpiryDate, isFound := GetMapKey("AAA")
fmt.Println("usrSessionExpiryDate: ", usrSessionExpiryDate, " isFound: ", isFound)

usrSessionExpiryDate, isFound = GetMapKey("BBB")
fmt.Println("usrSessionExpiryDate: ", usrSessionExpiryDate, " isFound: ", isFound)
}

// GetMapKey to get the specific key value from a Golang's Map
func GetMapKey(userName string) (int64, bool) {
userSessionExpiry, ok := UserSession[userName]
if !ok {
return userSessionExpiry, ok
}
return userSessionExpiry, ok
}