Why doesn't Go panic when trying to read a nil map?

WBOY
Release: 2024-02-06 10:00:04
forward
1089 people have browsed it

为什么 Go 在尝试读取 nil 映射时不会恐慌?

Question content

This is the code, I expected a panic when accessing mp["12"] but it fails It works fine there

// You can edit this code!
// Click here and start typing.
package main

import "log"

func main() {
    var mp map[string]int = nil
    log.Println(mp["12"], "12") // works fine
    if mp == nil {
        panic("map is nil") // panic here
    }
}
Copy after login

Correct answer


You can read from a nil map, but not write. The language specification says:

The above is the detailed content of Why doesn't Go panic when trying to read a nil map?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!