이번 장에서는 매번 하나의 인사말을 반환하는 대신
미리 정의 된 여러 인사말 메시지 중 하나를 반환하도록 코드를 변경해서 사용해보자.

여기서는 Go의 slice 를 사용하게 될 것이다.
slice란, java에서 사용하는 array와 같은 성격을 가지고 있다.
add, remove에 따라서 사이즈가 동적으로 변경된다.
Go에서 가장 많이 사용되는 타입 중 하나다.

그럼, slice에 3개의 인사메세지를 추가한후
랜덤하게 3개 인사말 중 하나를 리턴하도록 코드를 수정해보자.

 

1. greetings/greetings.go 코드를 아래와 같이 수정한다.

- randomFormat을 추가해서 랜덤한 인사말을 선택하도록 한다. randomFormat은 소문자로 시작하므로 자체 패키지의 코드에만 접근 가능하다. 
- randomFormat에서 세가지 메세지 형식을 slice에 선언한다. 선언할 때 괄호안의 크기를 생략하면(ex. [] String), 기본 배열이 동적으로 크기가 조정될 수 있음을 선언하는 것이다. 


- math/rand 패키지를 사용해서 랜덤한 숫자를 받아오도록 한다.
- 현재 시간으로 rand 패키지를 읽어오는 seed 함수를 init 함수에 추가한다.Go는 전역 변수가 초기화 된 후 프로그램 시작시 자동으로 초기화(init) 함수를 실행한다.
- 이제 Hello 파일에서 randomFormat 메서드를 호출하면, 랜덤한 메세지와 함께 입력받은 name이 출력될 것이다.

 

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
}

// 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 a randomly selected message format by specifying
    // a random index for the slice of formats.
    return formats[rand.Intn(len(formats))]
}


2. 이제 hello.go 가 있는 폴더로 이동해서 go build 해서 파일을 새로 읽어오도록 한 후 여러번 ./hello를 실행해보자.
각각 다른 결과가 호출 되는 것을 확인할 수 있다!

참고로 저번시간에 했던 error 처리 테스트를 위해서 name을 없앴다면 다시 hello.go 열어서 이름을 추가해주면 된다.

$ go build
$ ./hello
Great to see you, yunji!

$ ./hello
Hi, yunji. Welcome!

$ ./hello
Hail, yunji! Well met!

+ Recent posts