'golang naked return in function without named return
i have gone through some naked return/named returns(here) and similar question here but still have some doubts in my understanding on naked return. Below is code snippet from a rest api book im using
package main
import (
...
"github.com/julienschmidt/httprouter"
)
func main() {
router := httprouter.New()
router.GET("/api/v1/go-version", showVersion)
router.GET("/api/v1/show-file/:name", getFileContent)
log.Fatal(http.ListenAndServe(":8000", router))
}
func getCommandOutput(command string, arguments ...string) string {
out, _ := exec.Command(command, arguments...).Output()
return string(out)
}
func showVersion(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
response := getCommandOutput("/usr/local/go/bin/go", "version")
io.WriteString(w, response)
return /// what does this "return" give/do ?
}
func getFileContent(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
fmt.Fprintf(w, getCommandOutput("/bin/cat", params.ByName("name")))
}
why is the naked return used in func showVersion?
Solution 1:[1]
I’m not sure you chose the correct example. The return in showVersionis not a naked reurn since showVersion doesn’t return anything. A “naked return” occurs when the return types are given identifiers in the function signature. The return values are named at function declaration and don’t have to be declared in the function definition. The return in showVersion is not naked as the declaration of showVersion does not have named results. All the return in showVersion does is tell the process to exit out of the function. It’s not even needed.
However, on the subject of named results and naked returns, they essentially exist for brevity and code clarity (see Effective Go). You don’t have to use named results and naked returns. However, the documentation suggests it is “idiomatic”, which is what go code should strive to be.
However, as with all pieces of advice you need to decide if it truly is effective coding. Do named results really make the code more readable? I think so, because it makes clearer what the purpose of the function is. Do I use named results? Perhaps, not as often as I should.
If you want a definitive guide (beyond Effective Go), take a look at the go library. Does it use named results and naked returns? Make a note of how often and why. When they don’t use them, try to figure out why not. You will glean best practices. You might also want to take a look at the repostories for popular go libraries like gin. The Go language is constantly evolving and improving thanks to community feedback.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
