Slice Index - Multiple Return

202 views
Skip to first unread message

Michael Whatcott

unread,
Jun 19, 2021, 11:13:50 AM6/19/21
to golang-dev
Has anyone ever proposed a language change for slice access to have the option of double-return values, somewhat like map access?

Something like this?

a := []string{"1", "2"}
b, ok := a[0]
fmt.Println(b, ok) // output: "1", true
c, ok := a[4]
fmt.Println(c, ok) // output: "", false



Brad Fitzpatrick

unread,
Jun 19, 2021, 11:23:24 AM6/19/21
to Michael Whatcott, golang-dev
I don't recall seeing such a proposal before.

Want to file it?

--
You received this message because you are subscribed to the Google Groups "golang-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-dev+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-dev/8e07e5c6-f079-4fb6-8acf-bcdfb7e9ad2bn%40googlegroups.com.

Michael Whatcott

unread,
Jun 19, 2021, 11:38:19 AM6/19/21
to golang-dev
Yes, I think I would like to file such a proposal. Thanks for the quick reply and encouragement!

Jan Mercl

unread,
Jun 19, 2021, 11:40:53 AM6/19/21
to Michael Whatcott, golang-dev
On Sat, Jun 19, 2021 at 5:38 PM Michael Whatcott <mdwha...@gmail.com> wrote:

> Yes, I think I would like to file such a proposal. Thanks for the quick reply and encouragement!

I don't have a Github account, so let me please downvote this proposal here.

Michael Whatcott

unread,
Jun 19, 2021, 5:39:23 PM6/19/21
to golang-dev
Tell me more, Jan.

Ian Lance Taylor

unread,
Jun 19, 2021, 5:42:12 PM6/19/21
to Michael Whatcott, golang-dev
On Sat, Jun 19, 2021 at 8:13 AM Michael Whatcott <mdwha...@gmail.com> wrote:
>
The argument against this is that it's possible to write the
two-result function yourself in ordinary Go, doubly so with the
current generics proposal.

func Index[T any](s []T, i int) (v T, ok bool) {
if i < 0 || i >= len(s) {
return
}
return s[i], true
}

It is not possible to write the existing comma-ok forms in the
language without further additions.

Ian

Rob Pike

unread,
Jun 19, 2021, 7:26:16 PM6/19/21
to Ian Lance Taylor, Michael Whatcott, golang-dev
This has come up before, although perhaps not as a formal proposal. It doesn't seem worth the weight.

-rob


--
You received this message because you are subscribed to the Google Groups "golang-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-dev+...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages