Using underscore in return statements - a small convenience idea

135 views
Skip to first unread message

Nick Craig-Wood

unread,
Aug 23, 2023, 7:54:13 AM8/23/23
to golang-nuts
// Sometimes you end up typing this having to return
// a value you made up but don't care about.
func f1() (int, error) {
return -1, errors.New("something went wrong")
}

// Or maybe like this with named return values.
func f2() (a int, err error) {
return a, errors.New("something went wrong")
}

// It would be nice if you could type this instead.
//
// The underscore being used here to return whatever is in
// the return slot when the return statement is executed.
func f() (a int, err error) {
return _, errors.New("something went wrong")
}

The last doesn't compile of course, it gives

    cannot use _ as value or type

Being able to use _ seems like a nice convenience to me. What it actually returns is completely defined. And it would save us having to figure out types for stuff that you can't use `nil` for, eg `time.Time` is particularly annoying.

Thoughts?

Brian Candler

unread,
Aug 23, 2023, 9:51:37 AM8/23/23
to golang-nuts
Something similar is in the pipeline: https://github.com/golang/go/issues/61372

When implemented, it will be spelled "zero" rather than "_"

As I understand it, you'll still need to say 0, "" or nil where those are available for the type in question. Therefore in the f1() example you gave, you'll still need
return 0, errors.New("something went wrong")

Nick Craig-Wood

unread,
Aug 23, 2023, 10:10:19 AM8/23/23
to golang-nuts
Ah ha! I thought there would be a related issue I couldn't find :-)

`zero` would remove most of the pain though IMHO `_` looks neater in the return statements!

Thanks for the pointer Brian.

Sean Liao

unread,
Aug 23, 2023, 10:43:42 AM8/23/23
to golang-nuts

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/9393cf35-0831-4c5d-a0c8-da639e7443a2n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages