函數柯里化我理解,就是可以生成已經部分配置好的函數,這里的重點是生成新函數,因此,柯里化通常應用在需要一批不同的函數,但是這批函數除了部分代碼不一樣外,其他大部分都是相同的,這時,通過柯里化,能夠達到配置函數的目的,減少模板代碼
實際實例
在生產環境中,我們一般都會用到動態配置中心,一般動態配置中心的client會允許用戶監聽一個key,當key值變化后,可以執行用戶提供的回調函數,示例代碼如下:
tcc2.Watch(ctx, PcAppInfoKey, func(value string, err error) {
log := common.Logger(ctx)
if err != nil {
log.WithError(err).Error("tcc2 PcAppInfoKey watch failed")
return
}
err = json.Unmarshal([]byte(value), &pcApps)
if err != nil {
log.WithError(err).Error("pc apps json unmarshal failed")
return
}
}, time.Second * 30)
tcc2.Watch(ctx, MobileAppInfoKey, func(value string, err error) {
log := common.Logger(ctx)
if err != nil {
log.WithError(err).Error("tcc2 MobileAppInfoKey watch failed")
return
}
err = json.Unmarshal([]byte(value), &mobileApps)
if err != nil {
log.WithError(err).Error("mobile apps json unmarshal failed")
return
}
}, time.Second * 30)
可以發現,這里的回調函數往往大同小異,可以用柯里化來很方便的生成這些監聽函數,減少這些模板代碼
func listenKey(ctx context.Context, target interface{}, key string) func(value string, err error) {
return func(value string, err error) {
log := common.Logger(ctx)
if err != nil {
log.WithError(err).Errorf("tcc2 %s watch failed", key)
return
}
err = json.Unmarshal([]byte(value), target)
if err != nil {
log.WithError(err).Errorf("%s json unmarshal failed", key)
return
}
}
}
tcc2.Watch(ctx, PcAppInfoKey, listenKey(ctx, &PcApps, PcAppInfoKey), time.Second*30)
tcc2.Watch(ctx, MobileAppInfoKey, listenKey(ctx, &MobileApps, MobileAppInfoKey),time.Second*30)