我有这个:
var wd, _ = os.Getwd()
var advanceAgreementTemplateBytes, _ = ioutil.ReadFile(path.Join(wd, "/docs/templates/advance-agreement.template"))
var advanceAgreementTemplate = string(advanceAgreementTemplateBytes)
var t, _ = template.New("advance-agreement").Parse(string(advanceAgreementTemplate))
func sendAdvanceEmail(user *common.User, amount *apd.Decimal, fee *apd.Decimal, created time.Time) {
// use variables `t`, `advanceAgreementTemplate` etc here
}
我希望能够处理缓存变量中的错误,而不是使用_而不是err。唯一的方法是使用func init()
吗?
如果要对它们进行错误检查,请使用func init
或仅在main
中对其进行初始化。
并非所有呼叫都具有Must
变体,并且这种变体并非对所有呼叫都有意义。不要忘记The Go way是要进行正确的错误检查。为所有可能的失败调用使用Must
包装器会导致不良的编程风格,在默认情况下,每个错误都将崩溃,而不是处理和传播错误。
如果只需要在出错时使程序崩溃,编写自己的Must
包装程序就很容易。
编写自己的Must
包装器的好处是,您可以提供更好的错误消息-Go鼓励的另一件事。 ioutil.ReadFile
只会说“打开/docs/templates/advance-agreement.template:没有这样的文件或目录”