Last active
May 10, 2016 15:54
-
-
Save javi830810/d3391d9500644edcecb37804653efb38 to your computer and use it in GitHub Desktop.
My Dictionary
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 ( | |
"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