From 6f6fc081d34fae60889496c68790ebd969363ff2 Mon Sep 17 00:00:00 2001 From: Marcus Noble Date: Mon, 5 Oct 2020 13:44:28 +0000 Subject: [PATCH] Add 'content/posts/go-named-return-values.md' --- content/posts/go-named-return-values.md | 36 +++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 content/posts/go-named-return-values.md diff --git a/content/posts/go-named-return-values.md b/content/posts/go-named-return-values.md new file mode 100644 index 0000000..6697f14 --- /dev/null +++ b/content/posts/go-named-return-values.md @@ -0,0 +1,36 @@ +--- +title: "Named returns in Go functions" +date: 2020-10-05T15:50 +draft: false +tags: + - golang +images: +- /images/go-named-return-values.gif +--- + +While debugging some issues I was having with the AWS Golang SDK I discovered it was possible to name your function return values (pointers) and then set them within your function body without needing to explicitly return them at the end. + +E.g. + +```go +package main + +import "fmt" + +var greeting = "Hello, world" + +func main() { + fmt.Println(*test()) +} + +func test() (returnVal *string) { + returnVal = &greeting + return +} +``` + +Note the single `return` at the end of the function. + +I'm not really sure if this is a useful feature, feels more like it'd make code harder to read and could lead to some pretty nasty unintended mistakes when someone unfamilure with the code comes to make changes. Interesting either way. + +I'd be interested if anyone has any examples of where this kind of thing is beneficial. \ No newline at end of file