GO 언어 문법 (type에 method 추가하기) #3
2022. 3. 30. 10:47ㆍ99. 정리전 - IT/01. GO LANG
go version go1.18 windows/amd64
main.go | |
package main
import (
"fmt"
dict "scraping/typeExample/main/detail"
)
func main() {
// 이것은 Dictionary에 대한 Constructor가 아님!!!!!! dict := dict.Dictionary{"Donz": "I'm a boy"}
dict["hello"] = "I'm find"
fmt.Println("Setting :", dict) //-> Setting : map[Donz:I'm a boy hello:I'm find]
|
|
// Search
s, err := dict.Search("Donz")
if err != nil {
fmt.Println(" Search :", err) //->
} else {
fmt.Println(" Search :", s) //-> Search : I'm a boy
}
|
// Add
addErr := dict.Add("Donz", "She's a beat")
if addErr != nil {
fmt.Println(" Add :", addErr)
//-> Add : That word already exist }
|
// Modify
modifyErr := dict.Modify("Donz1", "He's Handsome")
if modifyErr != nil {
fmt.Println(" Modify :", modifyErr)
//-> Modify : Can't modify non-existing word } else {
s, _ := dict.Search("Donz")
fmt.Println(" Modify :", s) //->
}
|
// Delete
delErr := dict.Delete("Donz1")
if delErr != nil {
fmt.Println(" Delete :", delErr)
//-> Delete : Can't delete non-existing word } else {
_, err := dict.Search("Donz")
if err != nil {
fmt.Println(" Delete :", err) //->
}
}
|
}
|
anything_banking_file.go | |
package anything_dict_package
import "errors"
/*
1) Dictionary는 map[string]string의 alias 일 뿐 struct가 아님 (예) type Momey int -> Money(1) -> int 1 과 같은 뜻
2) struct 에만 method를 추가할 수 있는게 아님
3) type 에도 method 를 추가할 수 있음 (예) dictionary.Add() , dictionary.Delete() */
type Dictionary map[string]string
var (
errNotFound = errors.New("Can't find word ")
errWordExists = errors.New("That word already exist")
errCantModify = errors.New("Can't modify non-existing word")
errCantDelete = errors.New("Can't delete non-existing word")
)
|
|
// Search method - dict.Search("word")
func (d Dictionary) Search(word string) (string, error) { def, exist := d[word]
if exist {
return def, nil
} else {
return "", errNotFound
}
}
|
// Add method - dict.Add("word", "def")
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
}
|
// Modify method - dict.Modify("word", "def")
func (d Dictionary) Modify(word, def string) error { _, err := d.Search(word)
switch err {
case errNotFound:
return errCantModify
case nil:
d[word] = def
}
return nil
}
|
// Delete method - dict.Delete("word")
func (d Dictionary) Delete(word string) error { _, err := d.Search(word)
switch err {
case errNotFound:
return errCantDelete
case nil:
delete(d, word)
}
return nil
}
|
mod.go |
module scraping/typeExample/main
go 1.18
|