Created
June 1, 2019 01:24
-
-
Save utkarshmani1997/a0d174d31c8fcd47e4fa7598111edfb8 to your computer and use it in GitHub Desktop.
Idiomatic vs non-idiomatic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type myMap map[string]string | |
func (m myMap) contains(key string) (val string, ok bool) { | |
val, ok = m[key] | |
return val, ok | |
} | |
func (m myMap) add(key, value string) { | |
m[key] = value | |
} | |
func main() { | |
// non idiomatic | |
var m = make(map[string]string) | |
m["x"] = "hi" | |
if v, ok := m["x"]; ok { | |
fmt.Println(v) | |
} else { | |
fmt.Println("not found") | |
} | |
// idiomatic | |
var idiomaticM = make(myMap) | |
idiomaticM.add("x", "hi") | |
if v, ok := idiomaticM.contains("x"); ok { | |
fmt.Println(v) | |
} else { | |
fmt.Println("not found") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment