1

In Golang, zero values are used in case of an error. Eg, if a key is absent in a map[int]string, an empty string is returned.

I'm writing a function that takes in a url and returns the json string received on making an http request. If the error is not null, I would like to set the return value for the body to be a zero value byte array. Since a byte array can be cast into other data types, I can't figure out what to set it as. Maybe context dependent? Since I expect the returned value to be a string, I should set it to an empty string?

1 Answer 1

3

No, zero values are not idiomatically used as in-band error values. Map returns a zero value for keys not present, but that's an (often used) feature as one can, if required, test for the presence by the alternative syntax

v, ok := m[k]

Use multiple return values to return a value and a signal at the same time.

To signal a simple (true/false, ok/not ok, ...) condition, use a boolean value.

To signal an error condition, use an error typed value.

Etc.

BTW: The Go programming language has no casts. It has conversions and they're not the same as casts.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.