Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 자바편
- 목록처리
- 서버설정
- 티스토리 쿠키 삭제
- 이터레이터
- resttemplate
- baeldung
- iterator
- network configuration
- 데비안
- 친절한SQL튜닝
- 처음 만나는 AI 수학 with Python
- 처음 만나는 AI수학 with Python
- 페이징
- 선형대수
- /etc/network/interfaces
- 스프링 시큐리티
- 스프링부트핵심가이드
- 코드로배우는스프링웹프로젝트
- 네트워크 설정
- 알파회계
- 구멍가게코딩단
- 자료구조와함께배우는알고리즘입문
- 코드로배우는스프링부트웹프로젝트
- GIT
- 리눅스
- Kernighan의 C언어 프로그래밍
- ㅒ
- 자료구조와 함께 배우는 알고리즘 입문
- d
Archives
- Today
- Total
bright jazz music
Go -map type에 메소드 추가하기(Search) 본문
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
'Language > Go' 카테고리의 다른 글
| Go - map 타입에 메소드 추가하기(Update, Delete) (0) | 2021.02.19 |
|---|---|
| Go- map 타입에 메소드 추가하기(Add) (0) | 2021.02.19 |
| Go - 메소드2 (Go의 메소드 내부적 호출/ struct에 메소드 추가하기) (1) | 2021.02.18 |
| Go - method(기본사용법, 리시버, 에러처리 등, Withdraw) (0) | 2021.02.18 |
| Go - Account + NewAccount 캡술화/ func를 이용한 초기화 (0) | 2021.02.18 |
Comments
