Map पर Operations
m[key] = value
value := m[key]
value, ok := m[key]
delete(m, key)
length := len(m)
Adding and Updating Entries
m[key] = value से किसी key को assign करना अगर key अभी मौजूद नहीं तो एक नई entry जोड़ता है, या अगर मौजूद है तो मौजूदा value को overwrite करता है -- कोई अलग insert बनाम update operation नहीं है।
उदाहरण: Adding and Updating Entries
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Short declaration: create stock and infer the type
stock := map[string]int{"pens": 10}
stock["pens"] = 15
stock["pencils"] = 20
// Print the values followed by a newline
fmt.Println(stock)
}
Login to try C/C++/Java/PHP code in the editor
Deleting Entries
built-in delete function किसी map से एक key-value pair हटाता है। किसी ऐसी key के साथ इसे call करना जो मौजूद नहीं बिल्कुल सुरक्षित है और बस कुछ नहीं करता।
उदाहरण: Deleting Entries
package main
import "fmt"
func main() {
stock := map[string]int{"pens": 10, "pencils": 20}
delete(stock, "pencils")
delete(stock, "erasers") // no-op, key doesn't exist
fmt.Println(stock)
}
Login to try C/C++/Java/PHP code in the editor
Getting the Size of a Map
len() maps पर बिल्कुल वैसे ही काम करता है जैसे slices और strings पर, store की गई key-value pairs की current संख्या return करते हुए -- जब entries जोड़ी या हटाई जाती हैं यह अपने आप update होता है।
उदाहरण: Getting the Size of a Map
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Short declaration: create inventory and infer the type
inventory := map[string]int{"a": 1, "b": 2, "c": 3}
// Print the values followed by a newline
fmt.Println("entries:", len(inventory))
delete(inventory, "a")
// Print the values followed by a newline
fmt.Println("entries after delete:", len(inventory))
}
Login to try C/C++/Java/PHP code in the editor
- किसी ऐसी key को हटाने की कोशिश करना जो मौजूद नहीं और एक error की उम्मीद करना -- delete() गायब keys पर एक सुरक्षित no-op है।
- यह मान लेना कि len(m) map में वर्तमान में मौजूद key-value pairs की संख्या के अलावा कुछ और गिनता है।
- किसी slice या दूसरी non-comparable type (जैसे किसी दूसरे map) को map key के रूप में उपयोग करना, जो compile होने में fail होता है क्योंकि map keys comparable होनी चाहिए।
- किसी map entry को जोड़ना या update करना एक जैसा syntax उपयोग करता है: m[key] = value।
- delete(m, key) एक entry हटाता है, और key मौजूद न होने पर एक सुरक्षित no-op है।
- len(m) map में key-value pairs की संख्या return करता है।
- Map keys एक comparable type होनी चाहिए -- strings, numbers, और comparable fields वाले structs सभी qualify करते हैं।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: