Golang – 零值字节数组

huangapple go评论84阅读模式
英文:

Golang - zero value byte array

问题

在Golang中,当出现错误时会使用零值。例如,如果在map[int]string中找不到一个键,会返回一个空字符串。

我正在编写一个函数,它接受一个URL并返回通过进行HTTP请求收到的JSON字符串。如果错误不为空,我想将返回值的body设置为一个零值字节数组。由于字节数组可以转换为其他数据类型,我无法确定应该将其设置为什么。可能是上下文相关的?由于我期望返回值是一个字符串,所以应该将其设置为空字符串?

英文:

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

得分: 3

不,零值在习惯上不用作带内错误值。Map返回一个零值,表示键不存在,但这是一个(经常使用的)特性,因为如果需要,可以通过替代语法来测试存在性。

v, ok := m[k]

使用多个返回值同时返回一个值和一个信号。

要表示简单的(真/假,存在/不存在,...)条件,请使用布尔值。

要表示错误条件,请使用error类型的值。

等等。

顺便说一下:Go编程语言_没有_类型转换。它有类型转换,但它们与类型转换不同。

英文:

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.

huangapple
  • 本文由 发表于 2013年8月1日 23:54:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/17998873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定