자료구조 - map{ string:string }
\mydict\mydict.go
package mydict
import "errors"
// Doctionary map
type Dictionary map[string]string
var errNotFound = errors.New("not found")
var errWordExists = errors.New("that word already exists")
var errCantUpdate = errors.New("can not update, non-existing word")
// Search for a word
func (d Dictionary) Search(word string) (string, error) {
v, exists := d[word]
if exists {
return v, nil
} else {
return "", errNotFound
}
}
// Add a word to dictionary
func (d Dictionary) Add(word, def string) error {
_, err := d.Search(word)
switch err {
case errNotFound:
d[word] = def
case nil:
return errWordExists
}
return nil
}
// Update definition of a word
func (d Dictionary) Update(word, def string) error {
_, err := d.Search(word)
switch err {
case nil:
d[word] = def
case errNotFound:
return errCantUpdate
}
return nil
}
// Delete a word
func (d Dictionary) Delete(word string) {
delete(d, word)
}
\main.go
package main
import (
"GO/nomad/mydict"
"fmt"
)
func main() {
dictionary := mydict.Dictionary{}
fmt.Println("init:", dictionary)
word := "hello"
dictionary.Add(word, "First")
fmt.Println("after Add:", dictionary)
fmt.Println()
err1 := dictionary.Update(word, "Second")
if err1 == nil {
fmt.Println("after update(Second):", dictionary)
} else {
fmt.Printf("update error: %s \n", err1)
}
// update error case
err1 = dictionary.Update("word", "Second")
if err1 == nil {
fmt.Println("after update(Second):", dictionary)
} else {
fmt.Printf("update error: %s \n", err1)
}
fmt.Println()
result, _ := dictionary.Search(word)
fmt.Printf("search(%s) result: %s\n", word, result)
// delete
dictionary.Delete(word)
result, err := dictionary.Search(word)
if err != nil {
fmt.Printf("err >>> can not find '%s' and error code is '%s'", word, err)
} else {
fmt.Printf("definition(%s): %s", word, result)
}
}
[Running] go run "d:\workspace\GO\nomad\main.go"
init: map[]
after Add: map[hello:First]
after update(Second): map[hello:Second]
update error: can not update, non-existing word
search(hello) result: Second
err >>> can not find 'hello' and error code i
참고자료 [https://youtu.be/Rt8o1T1fDMo]
'GO lang' 카테고리의 다른 글
[GO] Scrapping(2) - Echo server (0) | 2021.10.15 |
---|---|
[GO] Scrapping(1) - URL checker (0) | 2021.10.07 |
[GO] channel (0) | 2021.10.07 |
[GO] 고루틴 (0) | 2021.10.07 |
[GO] 커스텀 패키지 만들기 (0) | 2021.10.06 |