I know I can iterate over a map m with
for k, v := range m { ... }
and look for a key, but is there a more efficient way of testing for a key’s existence in a map?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Here’s how you check if a map contains a key.
This initializes two variables.
valis the value of "foo" from the map if it exists, or a "zero value" if it doesn’t (in this case the empty string).okis aboolthat will be set totrueif the key existed.If you want, you can shorten this to a one-liner.
Go allows you to put an initializing statement before the condition (notice the semicolon) in the if statement. The consequence of this is that the scope of
valandokwill be limited to the body of the if statement, which is helpful if you only need to access them there.