在Go语言中使用有大小或无符号整数类型的原因有哪些?

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

What are reasons to use a sized or unsigned integer type in go?

问题

在《基础/基本类型》章节中进行Go Tour时,它说:

> 当你需要一个整数值时,除非你有特定的原因要使用大小或无符号整数类型,否则应该使用int。

那些特定的原因是什么?我们能列举出所有吗?

其他可用的资源只讨论了32位和64位的有符号和无符号类型。但为什么有人会使用小于32位的int类型呢?

英文:

Doing the go tour in chapter "Basics/Basic types" it says:

> When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.

What are those specific reasons? Can we name them all?

Other available ressources only talk about 32 and 64 bit signed and unsigned types. But why would someone use int types < 32 bit?

答案1

得分: 6

如果你想不出不使用标准的int的理由,那么应该使用标准的int。在大多数情况下,节省内存并不值得额外的努力,而且你可能也不需要存储那么大的值。

如果你要保存大量的小值,通过将数据类型更改为较小的类型(如byte),你可能能够节省大量的内存。将8位的值存储在int中意味着我们为每8位数据存储了24位的零,从而浪费了很多空间。当然,你可以通过一些位移操作,在int中存储4个(或者可能是8个)字节,但是为什么要自己费力呢,让编译器和CPU为你完成这些工作呢?

如果你尝试进行的计算可能无法适应32位整数,你可能需要使用int64或者甚至是bigint。

英文:

If you cannot think of a reason not to use a standard int, you should use a standard int. In most cases, saving memory isn't worth the extra effort and you are probably not going to need to store that large values anyway.

If you are saving a very large number of small values, you might be able to save a lot of memory by changing the datatype to a smaller one, such as byte. Storing 8bit values in an int means we are storing 24bits of zeroes for every 8 bits of data, and thus, wasting a lot of space. Of course, you could store 4 (or maybe 8) bytes inside an int with some bitshift magic, but why do the hard work when you can let the compiler and the cpu do it for you?

If you are trying to do computations that might not fit inside a 32bit integer, you might want an int64 instead, or even bigint.

huangapple
  • 本文由 发表于 2016年1月15日 01:31:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/34796020.html
匿名

发表评论

匿名网友

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

确定