dseve40868 2014-06-21 14:35
浏览 83
已采纳

是否有一个名为“ int32”的内置函数?

The below snippet works fine.
In this case, what "int32" is? A func?
I know there is a type named "int32"

This could be a stupid question. I've just finished A Tour of Go but I could not find the answer.(it's possible I'm missing something.)

package main

import "fmt"

func main() {
    var number = int32(5)
    fmt.Println(number) //5
}
  • 写回答

1条回答 默认 最新

  • duan0821 2014-06-21 14:37
    关注

    It is a type conversion, which is required for numeric types.

    Conversions are required when different numeric types are mixed in an expression or assignment. For instance, int32 and int are not the same type even though they may have the same size on a particular architecture.

    Since you do a variable declaration, you need to specify the type of '5'.
    Another option, as mentioned by rightfold in the comments is: var number int32 = 5

    (as opposed to a short variable declaration like number := 5)

    See also Go FAQ:

    The convenience of automatic conversion between numeric types in C is outweighed by the confusion it causes.
    When is an expression unsigned? How big is the value? Does it overflow? Is the result portable, independent of the machine on which it executes?

    It also complicates the compiler; “the usual arithmetic conversions” are not easy to implement and inconsistent across architectures.

    For reasons of portability, we decided to make things clear and straightforward at the cost of some explicit conversions in the code. The definition of constants in Go—arbitrary precision values free of signedness and size annotations—ameliorates matters considerably, though.

    A related detail is that, unlike in C, int and int64 are distinct types even if int is a 64-bit type.
    The int type is generic; if you care about how many bits an integer holds, Go encourages you to be explicit.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python验证码滑块图像识别
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)