Skip to content

Instantly share code, notes, and snippets.

@javi830810
Last active May 10, 2016 15:54
Show Gist options
  • Save javi830810/d3391d9500644edcecb37804653efb38 to your computer and use it in GitHub Desktop.
Save javi830810/d3391d9500644edcecb37804653efb38 to your computer and use it in GitHub Desktop.
My Dictionary
package main
import (
"errors"
"fmt"
)
type KeyPair struct{
key string
value string
}
type MyDict []KeyPair
func(dict MyDict) IndexOf(key string) int {
for i, value := range dict{
if value.key == key {
return i
}
}
return -1
}
func (dict MyDict) Exists(key string) bool {
return dict.IndexOf(key) != -1
}
func (dict MyDict) Insert(key string, value string) (MyDict, error) {
if dict.Exists(key) {
return nil, errors.New("Key already exists")
}
dict = append(dict, KeyPair{
key: key,
value: value,
})
return dict, nil
}
func main(){
d := MyDict{}
d, err := d.Insert("hello", "world")
d, err = d.Insert("hello2", "world2")
d, err = d.Insert("hello2", "world2")
if err == nil{
fmt.Println("Duplicated key it should have failed")
} else {
fmt.Println("All Good")
fmt.Println(d)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment