Language/Go

Go -map type에 메소드 추가하기(Search)

bright jazz music 2021. 2. 19. 00:16
package myDict

// type에도 메소드를 추가할 수 있다. struc에만 추가할 수 있는 것이 아니다.
// type 옆의 Dictionary는 map[string]string의 alias 같은 것임.

//Dictionary Type
type Dictionary map[string]string


메인

package main

import (
	"fmt"

	"github.com/hojuncha997/learngo/accounts/myDict"
)

func main() {
	dictionary := myDict.Dictionary{}
	dictionary["hello"] = "hello"
	dictionary["hello2"] = "hello2"
	fmt.Println(dictionary)
}


===

map[hello:hello hello2:hello2]

//하지만 이런 방식 말고 메소드를 사용하자

 

 

코드 수정

 

package myDict

import "errors"

// map은 struct가 아니다. array처럼 타입이다.
// type에도 메소드를 추가할 수 있다. struc에만 추가할 수 있는 것이 아니다.
// type 옆의 Dictionary는 map[string]string의 alias 같은 것임.

//Dictionary Type
type Dictionary map[string]string

var errNotFound = errors.New("Not Found")

// Search for a word
func (d Dictionary) Search(word string) (string, error) {
	//Dictionary라는 이름의 map에 Search 메소드를 더하는 것이다.
	//이 메소드는 string 타입을 word에 받고, string 또는 error로 반환한다.
	
    value, exists := d[word] // i, ok := m["key"] 여기서ok는 boolean임. i는 value
	if exists {
		return value, nil // 값이 없는 경우 nil 반환
	}
	return "", errNotFound
}


메인

package main

import (
	"fmt"

	"github.com/hojuncha997/learngo/accounts/myDict"
)

func main() {
	dictionary := myDict.Dictionary{"first": "First word"}
	//이렇게 하는 이유는 단어를 찾고 그 정의를 가져오기 위함이다.
	//fmt.Println(dictionary["first"]) 이렇게 해도 되지만 처리할 일이 많다

	definition, err := dictionary.Search("second") //Dictionary 안에서 "second"를 찾아라
   	//definition, err := dictionary.Search("first") //Dictionary 안에서 "first"를 찾아라
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(definition)
	}
}

====
 Not Found
 
 만약 찾는 값이 "first"라면
 
 ====
 First word