Go: Variables (Part 2)

This is a second post on Go programming language. You can read first post at - here.

Go is not just compiled programming language, but it is also statically typed programming language. You need to define a variable with its type. For example,

var x int

If this syntax looks a little awkward for you, read it in the way that makes sense. For example, the above declaration can be read as, define a variable x with type integer.

If the variable has initial value, you can assign it using assignment operator.

var x int = 2

You can define multiple variables using comma operator.

var x, y int

Again you can read these declaration as, defining variable x and y with type integer. If you know the initial values of x and y, then you can initialize them in just a single line using comma operator on right side of assignment operator.

var x, y int = 2, 3

Here, x will get 2 and y will get 3.

Go has couple of variation in integers. For example, int, int8, int16, int32 and int64. All these types save integers but the first save small number of integer value where as last save really big number of integer value. If you know that your variable never will have negative values then you can double the length of these integers by using unsigned integers such as uint, uint8, uint16, uint32 and uint64.

Like integer, you can also define variable with type floating point numbers. For floating points number, you need to use float32 or float64 type. For example,

var pi float32
var r float64

There is no such type with name float. So, please remember this.

While talking about the types, the other two popular types are string and boolean with string and bool type. You can define the variables with these types as follow.

var firstName string = "Bruce"
var isSupernatural bool = false
var lastName string
var married bool

Did you notice, how many times I wrote var? Four, right. We can eliminate this repetition by using () as follows.

var (
    firstName string = "Bruce"
    isSupernatural bool = false
    lastName string
    married bool
)

Much better, right? Let's create a new program with name var.go and define variables with each of these types. So far we know - integer, float, string and boolean. You know the basic needed code -

package main

func main() {

}

Let's define the variable with type integer.

package main

func main() {
    var x, y int = 2, 3
}

Let's run this program and see what happen.

$ go run hello.go
# command-line-arguments
./var.go:4:6: x declared and not used
./var.go:4:9: y declared and not used

We get errors! In Go, if you define variables, you must have to use it. Otherwise, your program wouldn't run. Even simple printing will work.

package main

import "fmt"

func main() {
    var x, y int = 2, 3

    fmt.Println(x, y)
}

So, what I did here is just use Println() function to print the value of defined variables in terminal. Also, Println() function is part of fmt package so that I imported it. Finally, just print the values of these variables by passing them as arguments. Let's run the program again.

$ go run var.go
2 3

So, we get the output! But, hey have you notice, I haven't added any spaces inside of Println() and still there is space between in output. This is because of Println() function. We'll talk about this space later because we are not currently interested in this space issue. For us, it looks good for now.

You can also define floating point variables.

package main

import "fmt"

func main() {
    var pi, r float64
    pi = 3.14
    r = 10

    fmt.Println(pi, r)
}

Now, if we run the program again -

$ go run var.go
3.14 10

Let's define variables with type string.

package main

import "fmt"

func main() {
    var (
        firstName string = "Bruce"
        lastName string = "Wayne"
    )

    fmt.Println(firstName, lastName)
}

Running this program produce the following output.

$ go run var.go
Bruce Wayne

Finally, let's define variables with type boolean.

package main

import "fmt"

func main() {
    var isMailSent bool

    fmt.Println(isMailSent)
}

If I run this program, it produce the following output.

$ go run var.go
false

From where this false came? In Go, when you define a variable, it set the initial value to zero values. The zero values for each type is different. For example, for integer it is 0. For floating point number it is 0.0. For string, its empty string "" and for Boolean, its false. Hence, we got the false. Go it?

That's it for the variables. I mean there are lot more to understand in Go for variables. But, as of now, what we learned is enough. We need to manipulate the values of defined variables, right? Otherwise what is the fun in doing programming?

Any questions?

The syntax for defining variables is little odd, any reason?: This "odd" syntax first introduce in Haskell programming language where they define variable like x:int or x has type integer. Because, they think defining a variable like int x is mistake in modern days. In old days when memory was limited, compiler first need to know the type of variable so that compiler can provide the memory based on type to upcoming variable x. That's not the case any more in modern days. So, let's define the variable in the way that make sense and x:int or var x int make sense if you read it like English - define a variable x with type int.

When you define r as floating point number, it print 10. I think it suppose to print 10.0: It does not matter what we think. But, still I can guarantee you that r is floating point number even though it print or evaluated as 10. To check the type of variable, you can use TypeOf() method from reflect package. Let me run one example for you -

package main

import "fmt"
import "reflect"

func main() {
    var r float64 = 10
    
    fmt.Println(reflect.TypeOf(r))
}

Now, if we run this program, it print -

$ go run var.go
float64

What is the difference between int and uint?: The main difference between these two types are unsigned. The first one accept negative number but second one not. Second one only accept positive numbers and due to that you almost get double size. Let's say you can save 7 numbers which are -3, -2, -1, 0, 1, 2, and 3. So, the range or limit for you is -3 to 3. But, I told you that you will never get negative number. In that case you can utilize those negative values on positive size and increase your limit as 0, 1, 2, 3, 4, 5 and 6. Now, with unsigned, you can save upto 6 where as previously you were saving upto 3. Got it?

Is it possible to run the program without using define variables?: I showed you that it is not possible. They have decided for language. If you are asking for some flags so that you can disable this type of errors, sorry there is no flag. You must have to use the define variable, otherwise don't define it at the first place.


Minenash picture

Just started reading through these, and I'm loving it so far. Two things though: 1. You didn't explain what the difference between the types of ints. From prior knowledge, I know the number is how many bits are used to store it, but what makes int different? Is it dynamic? Does it use 4 bits? 2. You don't have the link to the next part yet.

KC picture

Thanks for pointing out this. As of now, I added two links within text. I'll write a paragraph on this in simple words and then will update.

Minenash picture

I think you missed my 2nd 'point'. In your first Go post, you had a link at the bottom to go to this one, but on this post and part 3, you don't have a link to the next installment.

Soumyajit Pathak picture

Nice follow up.

Really like the FAQ like end notes. And now that I have seen this, I think these FAQ based format is a must for introductory pieces.

I am just curious about why there is no mention of := for short variable assignment (implicit type).

KC picture

Because of two reasons:

  1. It will make article lengthy. I need to introduce := itself, I need to explain type inference and also scope.
  2. To become more familiar with types so that in future when I introduce this short-hand, we already know types better.
Soumyajit Pathak picture

Great! I noticed the introduction of := in follow up article. Nice work

Rhett Trickett picture

This is a nice intro to Go, so far. Thanks Kiran! I like that you add a bit of background knowledge to explain why instead of just showing the how.

A few suggestions:

  1. If you add the Go tag to your post while editing it should improve the syntax highlighting when published. It will also include your post in the digest email for users who are following the Go topic on Able, which should increase your reads.
  2. Perhaps add a link from the end of part 1 to this post.
  3. Perhaps make the question text bold so that it's visually different from the answer text.

Just some ideas though. Keen to read the next post!

KC picture

Thanks for suggestions. Done.