Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ternary Operator Needed #39612

Closed
ebitogu opened this issue Jun 16, 2020 · 2 comments
Closed

Ternary Operator Needed #39612

ebitogu opened this issue Jun 16, 2020 · 2 comments

Comments

@ebitogu
Copy link

ebitogu commented Jun 16, 2020

I strongly think that a ternary operator is needed on Go

Here is why

I have a struct

type VerificationStatus struct {
	StatusCode    int
	StatusMessage string
	StatusData    interface{}
}

I wish to send that struct based on a json marshal like below


data, err := json.Marshal(struct {
					requestId string
				}{
					requestId: string(responseData),
				})

Now to send it back this is the long code I have to write


            if err != nil {
					return VerificationStatus{
						StatusCode:    http.StatusConflict,
						StatusMessage: "Verification Failed",
					}
				} else {
					return VerificationStatus{
						StatusCode:    http.StatusOK,
						StatusMessage: "Verification Started",
						StatusData:    data,
					}
				}

If we had a ternary operator I could have just done this


return VerificationStatus{
						StatusCode:    http.StatusOK,
						StatusMessage: "Verification Started",
						StatusData:    err==nil ? data : err.Error(),
					}

Thanks for this amazing language though.

@mvdan
Copy link
Member

mvdan commented Jun 16, 2020

This has been discussed before: #33171

If you think you have something new to add, please file a new proposal while filling the form at https://github.com/golang/proposal/blob/master/go2-language-changes.md.

@mvdan mvdan closed this as completed Jun 16, 2020
@martisch
Copy link
Contributor

martisch commented Jul 4, 2020

Now to send it back this is the long code I have to write

Note that the long code doesnt do the same then the proposed short form as StatusCode and StatusMessage are changed.

return VerificationStatus{
    StatusCode:     err==nil ? http.StatusOK : http.StatusConflict
    StatusMessage:  err==nil ? "Verification Started" : "Verification Failed"
    StatusData:     err==nil ? data : err.Error(),
}

starts to look much more complex to me to understand what err vs non err does then the version that uses one if.

@golang golang locked and limited conversation to collaborators Jul 4, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants