Skip to content

Instantly share code, notes, and snippets.

@utkarshmani1997
Created June 1, 2019 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save utkarshmani1997/a0d174d31c8fcd47e4fa7598111edfb8 to your computer and use it in GitHub Desktop.
Save utkarshmani1997/a0d174d31c8fcd47e4fa7598111edfb8 to your computer and use it in GitHub Desktop.
Idiomatic vs non-idiomatic
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