Go - Variables

Go - Variables

Variable

  • It is named unit of data and has assigned value, reference of values

  •     name-->"Peter"
        pincode-->900900
        grades-->99.08
    
  • If you change the values of variables, name remain same.

  •     name-->"Peter"
        pincode-->900900
        grades-->99.08
    
  • Syntax

  •     var <variable name> <data type> = <value>
        var s string = "hello World"
        var i int = 100
        var b bool = false
        var f float64 = 77.90
    
  • Example - main.go

  •     package main 
        import ("fmt") 
        func main () { 
           var greeting string = "Hello World"
           fmt.Println(greeting)
        }
        >>> go run main.go
        Hello World
    

Printing Variables

Printing a String

  • main.go

  •     package main
        import "fmt"
        func main() {
          fmt.Print("Hello World")
        }
    
        >>>go run main.go
        Hello World
    
  •     package main
        import "fmt"
        func main() {
          var city string = "Kolkata"
          fmt.Print(city)
        }
    
        >>>go run main.go
        Kolkata
    
  •     package main
        import "fmt"
        func main() {
          var name string = "Shounak"
          var user string = "Khulape"
          fmt.Print("Welcome to", name, ", ",user)
        }
    
        >>>go run main.go
        Welcome to Shounak, Khualpe
    

Now, the only problem with using print method is that does not introduce new line after the printing. So if we declare two variables and print one after the other on running the program both of them is printed next to each other the solution is new line character

package main
import "fmt"
func main() {
  var name string = "Shounak"
  var user string = "Khulape"
  fmt.Print(name)
  fmt.Print(user)
}

>>>go run main.go
ShounakKhualpe

Newline character

  1. \n is called the Newline character.

  2. It is used to create a new line.

  3. Place with string expressions.

  4. When inserted in a string, all the characters after \n are added to a new line.

 package main
 import "fmt"
 func main() {
   var name string = "Shounak"
   var user string = "Khulape"
   fmt.Print(name, "\n")
   fmt.Print(user)
 }


 >>>go run main.go
 Shounak
 Khualpe

We see the string Shounak was printed on new line

Println

  1. We have another printing packages that makes the printing of Newline process even more easier for us its called println
 package main
 import "fmt"
 func main() {
   var name string = "Shounak"
   var user string = "Khulape"
   fmt.Println(name)
   fmt.Println(user)
 }


 >>>go run main.go
 Shounak
 Khualpe

Notice we didn't use a new line character but the second print statement got printed on new line.

  1. Now you have notice that putting commas making more difficult to rescue it has printf function that implements formatted input-output

Printf

 fmt.Printf("Template string %s", Object args(s))

It is the process of inserting a custom string or variable in predefined text in golang printf function we can use from fmt package +, The function takes a template string that contains the text that needs to be formatted.

Printf-format specifier

Format specifiers tell Golang how to format different type of data types.

👉%v formats the value in a default format.

  var name string = "KodeKloud"
  fmt.Printf("Nice to see you here, at %v", name)

  >>> Nice to see you here, at Kodekloud

👉%d formats decimal integer.

  var grades int = 42
  fmt.Printf("Marks: %d", grades)

  >>> Marks: 42

Now let us use these format specifiers together.

main.go

  package main
  import ("fmt")

  func main() {
        var name string = "Joe"
        var i int = 78
        fmt.Printf("Hey, %v! You have scored %d/100 in Physics", name, i)
  }

  >>> go run main.go
      Hey, Joe! You have scored 78/100 in Physics

Here are few format specifiers we used in Golang

VerbDescription
%vdefualt format
%Ttype of the value
%dintegers
%ccharacter
%qquoted characters/string
%splain string
%ttrue or false
%ffloating numbers
%2ffloating numbers upto 2 decimal places

Declaring Variables

We can declare a variables in many ways, that is declaring and assigning it a value on the same line.

main.go

  package main
  import("fmt")

  func main() {
      var user string
      user = "Shounak"
      fmt.Pintln(user)
}

>>> go run main.go
    Shounak

Note data types of variables is also important as it defines what values may be assigned to it.

Caution

A variables with the type of string for example cannot be assigned a integer value so compiler throw error

Incorrect Value

  package main
  import ("fmt")

  func main () {
       var s string
       s = 123
       fmt.Println(s)
  }

  >>> go run main.go
  Error:cannot use 123 (type untyped int) as type string in assignment

shorthand way

  package main
  import ("fmt")

  func main() {
       var s,t string = "Shounak", "Khulape"
       fmt.Println(s)
       fmt.Println(t)
  }

  >>> go run main.go
      Shounak Khulape

The variables here are wrapped inside parenthesis after the var keyword but they are at different line

main.go

 package main
  import ("fmt")

  func main() {
       var (
       s string = "Shounak"
       i int = "Khulape"
       fmt.Println(s)
       fmt.Println(t)
  }

  >>> go run main.go
      Shounak Khulape

    s:="Hello Shounak"

main.go

  package main
  import ("fmt")

  func main() {
       name:= "Shounak"
       name = "Khulape"
       fmt.Println(name)
  }

  >>> go run main.go
      Khulape

If we try to modify its value to an integer and we run we will going to get error we cannot use which is an integer data type as type string in assignment

  package main
  import ("fmt")

  func main() {
       name:= "Shounak"
       name = 12
       fmt.Println(name)
  }

  >>> go run main.go
      Error: cannot use 12 (type untyped int) as type string in assignment

Variable scope

The scope of variable can be defined as a part of the program, where particular variable is accessible or from where it can be referenced. In Golang scope is defined using block (it is possibly empty sequence of declaration and statement within curly brackets)

  {
  // outer block
    {
    //  inner block
    }
  }
  1. Inner blocks can access variables declared within outer blocks.

  2. Outer blocks cannot access variables declared within inner blocks.

main.go

  func main() {
  city := "London"
  {
      country := "UK"
      fmt.Println(country)
      fmt.Println(city)
  }
  fmt.Println(country)
  fmt.Println(city)

  >>> go run main.go
      Error: ./main.go: Line 10: undefined: country

If we remove this line it will work fine

  func main() {
  city := "London"
  {
      country := "UK"
      fmt.Println(country)
      fmt.Println(city)
  }
  fmt.Println(city)

  >>> go run main.go
      UK
      London
      London

Local vs Global Variables

Local Variables

  1. Declared inside a function or a block.

  2. not accessible outside the function or the block

  3. can also be declared inside looping and conditional statements.

Let see example of Local Variables

Global Variables

  1. Declared outside if a function or a block.

  2. They are available throughout the lifetime of a program.

  3. declared at the top of the program outside all functions or blocks

  4. can be accessed from any part of the program.

  5. main.go

  6.     package main
        import ("fmt")
        var name string:= "Shounak"
        func main() {
    
             fmt.Println(name)
        }
    
        >>> go run main.go
            Shounak
    

That's great if you have make till here you have covered basic of Golang Variables

If you liked what you read, do follow and any feedback for further improvement will be highly appreciated!

Thank you and Happy Learning!👏