1

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?

Hari Krishnan
  • 5,992
  • 9
  • 37
  • 55

2 Answers2

3

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.

icza
  • 389,944
  • 63
  • 907
  • 827
  • Ok., I got it now. Thanks. So since i =1 and 1 is an integer, i will get integer as datatype. But another doubt is integer itself has int8, int16, int 64 as sub types ryt? So will i take int8 as default here? – Hari Krishnan Mar 29 '16 at 07:47
  • @HariKrishnan This expression: `1` is an **untyped** constant. If an expression is an untyped constant (and **not** a typed constant), then its **default type** is used which is `int` for untyped integer constants, as stated by the spec. If a **typed** constant is used, then obviously the type of the typed constant is used. – icza Mar 29 '16 at 07:49
0

Go is designed with ease of use in mind. So new variables are able to get an implicit type of the right side using the := operator. Also the constant 1 for example has an implicit type in go.

ikrabbe
  • 1,909
  • 12
  • 25