DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Go Variables
Samuel K.M
Samuel K.M

Posted on • Updated on

Go Variables

#go
How to declare variables?

There are 3 ways to declare variables:

1. Declare using var keyword, variable name & type

To declare a variable you will use the var keyword, followed by the the variable name and then the variable type.See the example below:

var i int
Enter fullscreen mode Exit fullscreen mode

you can then assign the variable using an equal sign

i = 20
Enter fullscreen mode Exit fullscreen mode

Type this in your Playground and run it:

package main

import (
    "fmt"
)

func main() {
    var i int
    i = 30
    fmt.Println(i)
}

//prints 30

Enter fullscreen mode Exit fullscreen mode
2. Declare using var keyword, variable name , and assign.

To declare a variable you will use the var keyword, followed by the the variable name and then the variable type and then assign the variable using an equal sign .See the example below:

var i int = 20
Enter fullscreen mode Exit fullscreen mode

Type this in your Playground and run it:

package main

import (
    "fmt"
)

func main() {
    var i int = 20
    fmt.Println(i)
}

//prints 20
Enter fullscreen mode Exit fullscreen mode
3 Declare without using var keyword and variable type

The go compiler provides for automatic type detection. To declare such, do as below:

i:=42
Enter fullscreen mode Exit fullscreen mode

Now run this in your playground:

package main
import (
    "fmt"
)

func main() {
    i := 42
    fmt.Println(i)
}

//prints 42
Enter fullscreen mode Exit fullscreen mode

The compiler automatically figures the type.

When should you use the different variable declaration?

U can use var i int when you want to use a variable without initializing it. For example where you want to assign the value in a for loop.
U can use var i int =20 when you want to have more control of your variable.
U can use i := 20 when you are comfortable with automatic type detection. As you work with go, u will note that the format := doesn't detect float 32 types and instead detects them as integers. Also this can't be used in package level variables as you will see later in this article. Case in example, run this in your playground:

package main

import (
    "fmt"
)

func main() {
    i := 32
    fmt.Printf("%v %T", i, i)
}

//prints 32 int
Enter fullscreen mode Exit fullscreen mode

Then run this:

package main

import (
    "fmt"
)

func main() {
    var i float32 = 32
    fmt.Printf("%v %T", i, i)
}

//prints 32 float32
Enter fullscreen mode Exit fullscreen mode

Note: You can also declare a variable at the package level. However in such cases you cant use := automatic type detection.

package main

import (
    "fmt"
)

//package level variable
var i float32 = 32

func main() {
   fmt.Printf("%v %T", i, i)
}

//prints 32 float32
Enter fullscreen mode Exit fullscreen mode
Declaring variable as a block

Let say for example you have want to describe a person, you would have to declare the following variables: Full names , gender , age ,Location as below:

package main

import (
    "fmt"
)

var name string = "Samuel Bazeng"
var gender string = "Male"
var age int = 24
var location string = "Nairobi"

func main() {

    fmt.Println(name)
    fmt.Println(gender)
    fmt.Println(age)
    fmt.Println(location)

}
Enter fullscreen mode Exit fullscreen mode

But as Go is designed to be clear and concise, we dont need to keep writing var on each variable we can simply wrap all variables in a block:

var(
name string = "Samuel Bazeng"
gender string = "Male"
age int = 24
location string = "Nairobi"
)
Enter fullscreen mode Exit fullscreen mode

When you run the code below it still works:

package main

import (
    "fmt"
)
var(
name string = "Samuel Bazeng"
gender string = "Male"
age int = 24
location string = "Nairobi"
)

func main() {

    fmt.Println(name)
        fmt.Println(gender)
        fmt.Println(age)
        fmt.Println(location)

}
Enter fullscreen mode Exit fullscreen mode

This way of declaring variable can also help in grouping variables by function.

Reassigning Variable

In case of reassignment, Go considers the variable within the innermost scope. This is called shadowing. Case in example , the code below will print 10 instead of 20.

package main

import (
    "fmt"
)
var i int =20;
func main() {
    var i int =10
    fmt.Println(i)
}
Enter fullscreen mode Exit fullscreen mode

Note: You cant use := to redeclare a variable, it will result to an error.

Important Points To Note While Working With Variables:
  1. Every variable declared must be used. Failure to do so results into an error. Try this on your playground.
package main

import (
    "fmt"
)
var i int =20;
func main() {
    var i int =10
    k := 11
    fmt.Println(i)

}

// ./prog.go:9:2: k declared but not used
//Go buid failed
Enter fullscreen mode Exit fullscreen mode
Naming Variables

There are two sets of rules you need to keep track of:
1 .How naming controls the visibility of variables.

  • Lower case variables are scoped to the package. Any file in the same package can access the variable. For example the variable var i int =20 in the example below:
package main

import (
    "fmt"
)

var i int = 20

func main() {
    var i int = 10
    fmt.Println(i)
}

Enter fullscreen mode Exit fullscreen mode
  • Upper case variables are exported and are available globally.For example the variable var I int =20 in the example below:
package main

import (
    "fmt"
)

var I int = 20

func main() {
    var I int = 10
    fmt.Println(I)

}
Enter fullscreen mode Exit fullscreen mode
  • Variable defined in a block are scoped to the block and aren't visible outside the block.For example
func main() {
    var i int = 10
    fmt.Println(i)
}
Enter fullscreen mode Exit fullscreen mode

2.Naming Conventions

There are a few rules we should follow:

  1. The length of a variable name should reflect its lifeline. var i int is perfect for a for loop and other places where you don't have to keep it in your head for a long time. In a case where you will use a variable quite often its better to have a longer name example var firstName string
  2. For a package level variable its good to use a verbose name and clear enough for someone who is outside the source life to understand.
  3. Use Pascal or Camel Case
//pascal case
 var ThisShouldBePascalCase string = "Pascal"
 var thisShouldBeCamelCase string = "camelCase"
Enter fullscreen mode Exit fullscreen mode
Variable Typecasting / Conversion

Type conversion happens when we assign a value of one data type to another data type. There are two types of Data type conversion available in Programming.

  • Implicit Type Conversion: Implicit type conversion, also known as coercion, is an automatic type conversion by the compiler. Some languages allow or even require compilers to provide coercion. Golang does not support implicit type conversion because of its robust type system.

  • Explicit Type Conversion: Explicit type conversion is special programming instruction that specifies what data type to treat a variable as in a given expression. For example, casting will ignore β€œextra” information (but never adds information to the type being cast).

Go uses Explicit Type Conversion

Syntax of type conversion
newDataTypeVariable = newType(oldDataTypeVariable)
Enter fullscreen mode Exit fullscreen mode

For example:

package main

import (
    "fmt"
)

func main() {
    var i int = 10
    var j float32
    j = float32(i)
    fmt.Printf("%v %T", j, j)

}

//prints 10 float32
Enter fullscreen mode Exit fullscreen mode

An example where typecasting ignores β€œextra” information:

package main

import (
    "fmt"
)

func main() {
    var i float32 = 10.5
    var j int
    j = int(i)
    fmt.Printf("%v %T", j, j)

}

//prints 10 int ignoring .5
Enter fullscreen mode Exit fullscreen mode
String Conversions

String conversion are a bit different. For example try running the code below results into an error:

package main

import (
    "fmt"
)

func main() {
    var i int = 10
    var j string
    j = string(i)
    fmt.Printf("%v %T", j, j)

}

//conversion from int to string yields a string of one rune, not a string of digits (did you mean fmt.Sprint(x)?)

Enter fullscreen mode Exit fullscreen mode

You can use:

package main

import (
    "fmt"
)

func main() {
    var i int = 10
    var j string
    j = fmt.Sprint(i)
    fmt.Printf("%v %T", j, j)
}

Enter fullscreen mode Exit fullscreen mode

or you can also use the strconv package.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    var i int = 10
    var j string
    j = strconv.Itoa(i)
    fmt.Printf("%v %T", j, j)

}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.