dqaq59269 2016-03-29 07:33
浏览 29
已采纳

在Go编程语言中定义变量

I am learning Go language and comes across seeing this type of variable declaration:

i:=1;

But it says that Go has static variables. i,e variables should be defined in some way like this

var i int=1;

So what is the difference between these two methods? In the first one we don't need to indicate the data type. Why is it so?

  • 写回答

2条回答 默认 最新

  • doumian3780 2016-03-29 07:37
    关注

    The first one i := 1 is called short variable declaration. It is a shorthand for regular variable declaration with initializer expressions but no types:

    var IdentifierList = ExpressionList
    

    You don't specify the type of i, but i will have a type based on certain rules. Its type will be automatically inferred. In this case it will be of type int because the initializer expression 1 is an untyped integer constant whose default type is int, so when a type is needed (e.g. it is used in a short variable declaration), int type will be deduced.

    So Go is statically typed. That means variables will have a static type and values stored in them at runtime will always be of that type. Being statically typed does not mean you have to explicitly specify the static type, it just means variables must have a static type - decided at compile time - which condition is met even if you use short variable declaration and you don't specify it.

    Note that you can also omit the type if you declare a variable with the var keyword:

    var i = 1
    

    In which case the type will also be deduced from the type of the initializer expression.

    Spec: Variable declaration:

    If a type is present, each variable is given that type. Otherwise, each variable is given the type of the corresponding initialization value in the assignment. If that value is an untyped constant, it is first converted to its default type; if it is an untyped boolean value, it is first converted to type bool. The predeclared value nil cannot be used to initialize a variable with no explicit type.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示