Anonymous Struct in Go
tags: learning go programming
content
if err := resultsTemplate.Execute(w, struct {
Results google.Results
Timeout, Elapsed time.Duration
}{
Results: results,
Timeout: timeout,
Elapsed: elapsed,
}); err != nil {
log.Print(err)
return
}breaking down this code:
- basic structure:
if err := doSomething(); err != nil { handleErr } doSomethingistmpl.Execute(w, data)datais a struct- the struct is an anonymous struct
- the above code is the same as below:
type TempStruct struct {
Results google.Results
Timeout time.Duration
Elasped time.Duration
}
tempStruct := TempStruct {
Results: results,
Timeout: timeout,
Elapsed: elapsed,
}
if err := tmpl.Execute(w, tempStruct); err != nil { }