함수 서명을 사용자 정의 타입으로 사용
마찬가지로 현재 코드 문맥에 맞는 의미를 부여하기 위해 함수 서명을 사용자 정의 타입으로 정의하는 것도 유용하다.
type quantity int type costCalculator func(quantity, float64) float64 func describe(q quantity, price float64, c costCalculator) { fmt.Printf("quantity: %d, price: %0.0f, cost: %0.0f\n", q, price, c(q, price)) } func main() { var offBy10Percent, offBy1000Won costCalculator offBy10Percent = func(q quantity, price float64) float64 { return float64(q) * price * 0.9 } offBy1000Won = func(q quantity, price float64) float64 { return float64(q)*price - 1000 } describe(3, 10000, offBy10Percent) describe(3, 10000, offBy1000Won) }
실행 결과
quantity: 3, price: 10000, cost: 27000 quantity: 3, price: 10000, cost: 29000
costCalculator와 서명이 일치하는 함수를 만들었고 이를 describe() 함수의 매개변수로 전달했다. 기본 서명인 func(quantity, float64) float64를 사용하는 것보다 costCalculator 타입을 사용하는 것이 더 가독성이 높고 의미도 분명하게 전달된다.