Variables In 'Go'(Learn 'Go' - Part 8)

in #programming7 years ago (edited)

Variables allow you to build useful programs, you cannot do much with the basic types. They are specific storage locations with a name and a specific type.

 

For instance,

 

package main

import "fmt"

func main(){
var x string = "Hello World"
fmt.Println(x)
}

 
 

Just like the first program, this program will also print "Hello World" on the screen. However, we have created a variable called 'x' and a type 'String'.

 

In Go, we use the 'var' keyword to create a variable, then specify a name for it and then declare its type.

 

We can set its value right after creating it like we did in the code above or in the next statement.

 

var x string

x = "Hello World"

 
 

It is important to note than "=" sign is used to denote a value to something in Go and it does not mean 'is equal to'. We use "==" to set a value equal to something like we use "=" in mathematical expressions.

 

For instance, when we use 'x = x + y', the current value of x gets added to the current value of y and x gets a new value. The value of x can vary because it is a variable. To make things even simpler, we can also use 'x += y' instead of 'x = x + y', it basically means the same.

 
 

To keep things simple and short for the developers, Go allows us to create a variable with a starting value.

 

For instance,

 

x := "Hello World"

x := 5

 
 

Go assigns a 'type' to the variable based on the literal value. It is always better to use these shorter forms of code while creating a variable.

 
 
 

Naming A Variable

You should use a name that describes the variable so that you or the other developers can make a sense out of it later. In Go, variable names must begin with a letter and they may contain letters, numbers and underscore. You can use camel casing to make a variable name easily readable, i.e., using Capital letter for every new word in the sequence. For e.g., 'helloWorldHowAreYou'. It is easier to read than 'helloworldhowareyou'. The first letter has to be in lowercase.

 
 

Scope Of Using A Variable

If the variable has been declared outside of a function, all the functions can access it. However, if you declare a variable within a particular function, only that function can use it.

 
 
 

Previous Posts In The Series

 
 

Introduction To 'Go' Programming Language(Learn 'Go' - Part 1)

 

25 Basic Keywords Of The Go Programming Language (Learn 'Go' - Part 2)

 

How To Set The Go Programming Environment On Your System?(Learn 'Go' - Part 3)

 

Create Your First Program In Go Language (Learn 'Go' - Part 4)

 

Strings In 'Go'(Learn 'Go' - Part 5)

 

Booleans In 'Go'(Learn 'Go' - Part 6)

 

Numbers In 'Go'(Learn 'Go' - Part 7


 
 

Upcoming Posts

 

Constants In 'Go'(Learn 'Go' - Part9)

Coin Marketplace

STEEM 0.21
TRX 0.26
JST 0.040
BTC 101164.87
ETH 3696.45
USDT 1.00
SBD 3.19