본문 바로가기

SW LAB/Go Lang

[Google Go 언어] 미니 프로젝트 : Dictionary

Step 1

  • Struct 를 이용하여 내부 func를 활용한 func 를 만들어보자
  • 단어를 추가하고 에러 처리를 해보자
  • `mydict.go`
package mydict

import "errors"

// Dictionary type
type Dictionary map[string]string

var errNotFound = errors.New("Not Found")
var errWordExists = errors.New("That word already exists")

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

// Add a word to the 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
}
  • `main.go`
package main

import (
	"fmt"
	"kjham/learngo_dictionary/mydict"
)

func main() {
	dictionary := mydict.Dictionary{"first": "First word"}
	word := "Hello"
	definition := "Greeting"
	err := dictionary.Add(word, definition)
	if err != nil {
		fmt.Println(err)
	}
	hello, _ := dictionary.Search(word)
	fmt.Println("found", word, "definition:", hello)
	err2 := dictionary.Add(word, definition)
	if err2 != nil {
		fmt.Println(err2)
	}
}

Step 2

  • 단어를 수정하거나 삭제를 해보자
  • `dict.go`
package mydict

import "errors"

// Dictionary type
type Dictionary map[string]string

var (
	errNotFound   = errors.New("Not Found")
	errCantUpdate = errors.New("Can't update non-existing word")
	errWordExists = errors.New("That word already exists")
)

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

// Add a word to the 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 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 (
	"fmt"
	"kjham/learngo_dictionary/mydict"
)

func main() {
	dictionary := mydict.Dictionary{"first": "First word"}
	word := "Hello"
	err := dictionary.Add(word, "First")
	if err != nil {
		fmt.Println(err)
	}
	err2 := dictionary.Update(word, "Second")
	if err2 != nil {
		fmt.Println(err2)
	}
	hello, _ := dictionary.Search(word)
	fmt.Println("found", word, "definition:", hello)
	dictionary.Delete(word)
	find, err3 := dictionary.Search(word)
	if err3 != nil {
		fmt.Println(err3)
	} else {
		fmt.Println(find)
	}
}