Go lang - 7 : 함수를 값처럼 쓰기

개발조아·2022년 3월 26일
0

go-lang

목록 보기
7/13

맵에 넣은 이후 꺼내서 쓰기

package main

import (
	"fmt"
	"strconv" // strconv 는 문자열와 대응하는 타입을 서로 변경해주는 패키지입니다.
)

func add(i, j int) int { return i + j }
func sub(i, j int) int { return i - j }
func mul(i, j int) int { return i * j }
func div(i, j int) int { return i / j }

var opMap = map[string]calculatorType{
	"+": add,
	"-": sub,
	"*": mul,
	"/": div,
}

type calculatorType func(int, int) int	// 함수 타입 지정

func main() {
	calculateLists := [][]string{
		{"5", "+", "3"},
		{"5", "-", "3"},
		{"5", "*", "3"},
		{"5", "/", "3"},
		{"5", "%", "3"},
		{"Five", "%", "three"},
		{"5"},
	}

	for _, calculate := range calculateLists { // 안 쓸 변수는 _ 표시를 해줍니다.
		if len(calculate) != 3 { // 숫자 연산자 숫자 포맷을 가져야해서 유효성 검사합니다.
			fmt.Println("포맷이 다릅니다. 입력 : ", calculate)
			continue // 다음 for 문으로 넘어갑니다.
		}
		// 숫자인지 검사
		num1, err := strconv.Atoi(calculate[0]) // ASCII to integer = 문자를 integer 로 바꿔주는 함수
		if err != nil { // error 에 뭔가 있다! (즉, 에러발생)
			fmt.Println(err)
			continue
		}
		// 연산자인지 검사 후 함수 가져오기
		operator := calculate[1]
		resultFunc, ok := opMap[operator]
		if !ok {
			fmt.Println("지원하지 않는 연산자입니다. 입력 : ", operator)
			continue
		}
		// 숫자인지 검사
		num2, err := strconv.Atoi(calculate[2])
		if err != nil {
			fmt.Println(err)
			continue
		}

		// 가져온 함수 실행 !
		result := resultFunc(num1, num2)
		fmt.Println(result)

	}

}

아래처럼 함수의 형태를 명시 할 수 있는 Type 지정을 해주었다.

type calculatorType func(int, int) int

추후 문서화나 테스트를 찍어낼때 활용하기 좋은 방법에 힌트가 될것같다..

나중에 코딩테스트 공부할 때를 대비해서
strconv 패키지같은 Convert 패키지를 정리해둬야겠다.

Console

profile
https://github.com/askePhoenix

0개의 댓글