딕셔너리 만들기

mydict.go

package mydict

import "errors"

// Dictionary type
type Dictionary map[string]string

// Error
var (
	errNotFound   = errors.New("Not Found")
	errWordExists = errors.New("That word already exists")
	errCantUpdate = errors.New("Cant update non-existing word")
)

// Search for a word
func (d Dictionary) Search(word string) (string, error) {
	value, exists := d[word]
	if exists {
		return value, nil // nil => 0 value
	}
	return "", errNotFound
}

// Add a word to the dictionary
func (d Dictionary) Add(word, def string) error {
	//word와 def를 입력받아 error만 리턴함
	_, err := d.Search(word)
	switch err {
	case errNotFound:
		d[word] = def
	case nil:
		return errWordExists
	}
	return nil
}

// Update a word to the dictionary
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 to the dictionary
func (d Dictionary) Delete(word string) {
	//삭제는 이미 있는 기능을 사용하는데, 만약 딕셔너리 안에 word가 없으면 아무것도
	//리턴하지 않기에 error도 리턴 할 필요가 없고, 있으면 삭제된다.
	delete(d, word)
}

 

main.go

package main

import (
	"fmt"
	"test1/mydict"
)

func main() {
	dictionary := mydict.Dictionary{}

	baseWord := "hello"
	dictionary.Add(baseWord, "First")
	word, _ := dictionary.Search(baseWord)
	dictionary.Delete(baseWord)
	word, err := dictionary.Search(baseWord)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(word)
	}
}

+ Recent posts