참조: https://go.dev/doc/tutorial/greetings-multiple-people
- 개요
이번에는 여러 개의 이름을 함수로 넘겨서 각 이름에 대한 인삿말을 반환하도록 코드를 수정해보자.
- slice와 map
지금은 학습을 목적으로 코드를 작성하고 있으므로 Hello 함수의 인자와 반환형을 곧바로 변경해도 큰일이 일어나지 않는다. 그래도 좀 더 그럴싸한 상황을 가정해서 이미 greetings 모듈이 배포되어 사용하고 있다고 가정해보자. 이럴 때 Hello 함수의 인자와 반환형을 변경해서 배포해버리면 기존 사용자들의 프로그램이 제대로 동작하지 않을 수 있다.
이런 상황에서는 여러 인삿말을 반환하는 신규 함수를 추가해야 한다. 이렇게 하면 기존 함수의 호환성을 그대로 유지할 수 있다. greetings.go 에 아래 코드를 복사한다.
package greetings
import (
"errors"
"fmt"
"math/rand"
"time"
)
// Hello returns a greeting for the named person.
func Hello(name string) (string, error) {
// If no name was given, return an error with a message.
if name == "" {
return name, errors.New("empty name")
}
// Create a message using a random format.
message := fmt.Sprintf(randomFormat(), name)
return message, nil
}
// Hellos returns a map that associates each of the named people
// with a greeting message.
func Hellos(names []string) (map[string]string, error) {
// A map to associate names with messages.
messages := make(map[string]string)
// Loop through the received slice of names, calling
// the Hello function to get a message for each name.
for _, name := range names {
message, err := Hello(name)
if err != nil {
return nil, err
}
// In the map, associate the retrieved message with
// the name.
messages[name] = message
}
return messages, nil
}
// Init sets initial values for variables used in the function.
func init() {
rand.Seed(time.Now().UnixNano())
}
// randomFormat returns one of a set of greeting messages. The returned
// message is selected at random.
func randomFormat() string {
// A slice of message formats.
formats := []string{
"Hi, %v. Welcome!",
"Great to see you, %v!",
"Hail, %v! Well met!",
}
// Return one of the message formats selected at random.
return formats[rand.Intn(len(formats))]
}
이 코드의 의미는 아래와 같다.
- Hellos 함수를 추가하였다. 파라미터로 names slice 형을, 반환 형으로 map 을 반환한다.
- Hellos 신규 함수에서는 Hello 함수를 재활용한다. 이렇게 하면 코드 중복을 줄일 수 있다.
- 이름과 각 이름에 대한 인삿말을 맵핑하기 위해 messages map 을 선언했다. Go 에서 map 을 초기화할때에는 make(map[key-type]valye-type) 와 같은 문법을 사용한다.
- names 에 대해 for 문을 사용했다. range 는 2 개의 값, 현재 요소의 index 와 현재 요소의 value 를 반환한다. 예제에서는 index 가 필요 없는데 이럴 때에는 언더스코어(_)로 표현된 Go blank identifier 로 무시할 수 있다.
hello.go 에서도 slice 이름형을 넘기도록 한다.
// A slice of names.
names := []string{"Gladys", "Samantha", "Darrin"}
....
messages, err := greetings.Hellos(names)
'Language > Go' 카테고리의 다른 글
Go - compile 과 install (0) | 2021.11.28 |
---|---|
Go - test (0) | 2021.11.28 |
Go - random 과 slice (0) | 2021.11.28 |
Go - Return 과 handle an error (0) | 2021.11.28 |
Go - called module 과 caller module (0) | 2021.11.28 |
댓글