#golang #go #maps
Map - key value pairs (index and value associated with the index)
Un ordered collection
----
1. Creating a Map
2. Initializing a map
3. Maps and Slices - Slices can't be a key for a map, whereas they can be a value
4. Nil Map
5. Retrieve values from Map
6. Iterating a Map - For Range
7. Removing item from Map
mapdemo.go
----------
package main
import "fmt"
func main(){
a:=make(map[int]string) //Creating a map with integer key and string values
b:=map[int]string{1:"one",2:"two",3:"one"} //Initialize a map with key and value
//Maps will allow duplication in values but not in keys
fmt.Println(a)
fmt.Println(b)
}
mapslicedemo.go
-----------------
package main
import "fmt"
func main(){
a:=map[int][]string{} //Trying to create a map with key of type integer slice
//Map keys should not be slices
fmt.Println(a)
}
mapdeclaredemo.go
-----------------
package main
import "fmt"
func main(){
var b map[string]string //Declaration of map b - nil map (map is neither initialized nor created)
a:=map[string]string{}
a["name"]="Jack" //initialize map after declaration
a["address"]="2nd Street"
a["city"]="Coimbatore"
b["name"]="Ram"
fmt.Println(a)
fmt.Println(b)
}
mapfetchdemo.go
---------------
package main
import "fmt"
func main(){
address:=map[string]string{"street":"1st Street","city":"Coimbatore","country":"India"}
fmt.Println(address) //Prints the entire map contents
//I need to check whether a key "street" is available in the map, if so, fetch the value
value,result:=address["street"] //Lookup returns two values, 1.value of the map found in the key,2. boolean which says whether the key exists or not
if result {
fmt.Println(value)
}else {
fmt.Println("Key not found")
}
value1:=address["name"] //If a key is non-existent in a map, the value returned will be ""
if value1!="" {
fmt.Println(value1)
}else {
fmt.Println("Key not found")
}
}
iteratemapdemo.go
-----------------
package main
import "fmt"
func main(){
a:=map[string]string{"name":"Ram","state":"Tamilnadu"}
for k,v:=range a { //Iterating maps using for-range loop with key and values
fmt.Printf("Key is %s, and value is %s\n",k,v)
}
delete(a,"state") //Delete a key-value pair from the map
for k,v:=range a {
fmt.Printf("Key %s,Value %s\n",k,v)
}
}
Watch video Go (golang) Tutorials - Maps online, duration hours minute second in high quality that is uploaded to the channel Ambasoft Java 28 March 2018. Share the link to the video on social media so that your subscribers and friends will also watch this video. This video clip has been viewed 462 times and liked it 11 visitors.