4 ms·
I guess it's because the templates don't have to ever be parsed since they're transpiled to Go code at compile-time. It's been a while since I've used Go's temp
by landr0id 10y ago
I guess it's because the templates don't have to ever be parsed since they're transpiled to Go code at compile-time. It's been a while since I've used Go's template packages but I thought that they're only parsed once no matter how many times you execute it (assuming reuse of the Template struct). So to me, it seems there should really be no difference from just putting the initialization of the template in an init() func.
- chewxy 10y agoNothing is stopping you from doing something stupid like this though: func AtRuntime(writer io.Writer){ templ := template.Must(template.New("blah").Parse(templateText)) templ.Execute(writer, someStructhere) } Though most sane devs would put the template parsing code in init()
- leetrout 10y agoThis brings up another question... Couldn't you just put them in the global namespace in the package? I also don't see the need for init since this is just parsing / compiling a template one time. Maybe I'm just not a sane dev? I just put all my template and regex "must" statements as global vars in my package close to where they're used.
- randomdata 10y agoMost definitely, if you want the compiled template loaded for the life of the application, at least. The documentation for template.Must says it is intended to be used exactly like that. If you were in a regular code block, you would check the error and handle it more gracefully.