Go - Variables and Constant

Go - Variables and Constant

Zero Values

What is zero values in Golang?

In Golang if you're declaring a new variable, but are not necessarily initializing it with a value, the variable is given default values is called zero value.

1.bool-->false 2.int-->0 3.float64-->0.0 4.string-->""

Pointer, function values is nil

main.go

  package main
  import "fmt"

  func main() {
        var i int
        fmt.Printf("%d", i)
  }

  >>> go run main.go
  0

main.go

  package main
  import "fmt"

  func main() {
        var f1 float64
        fmt.Printf("%.2f", f1)
  }

  >>> go run main.go
  0.00
VerbDescription
int0
float640.0
string""
boolfalse
pointers, functions, interfaces, mapsnil

User Input

We will see how to read input from a user.

Scanf

One ways to take input is through scanner function, which is provided by the FMT package.

fmt.Scanf("% (s)", Object_arguments)

Scanner function takes the format string, along with the list of variable number of arguments. The String contains custom specifiers that the scanner function uses to format final output string, The list is the list of all arguments where you want to store your data.

main.go

package main
  import"fmt"

  func main() {
      var name string
      fmt.Print("Enter your name:")
      fmt.println("Hey there, ", name)
  }

  >>> go run main.go
      Enter your name: Shounak
      Hey there, Shounak

main.go

 package main
  import"fmt"

  func main() {
      var name string
      var is_muggle bool
      fmt.Print("Enter your name & are you a muggle:")
      fmt.Scanf("%s %t", &name, &is_muggle)
      fmt.println(name, is_muggle)
  }

  >>> go run main.go
      Enter your name & are you a muggle: Shounak false
      Shounak false

Scanf function reads from the input source sequentially. Hence we must give list of argument in the order that specified in format string

count-> the number of arguments that the fucntion writes to

error-> any error thrown during the execution of the function

Multiple Input

main.go

package main
  import"fmt"

  func main() {
      var a string
      var b int
      fmt.Print("Enter a string and a number:")
      count, err := fmt.Scanf("%s %d", &a &b)
      fmt.println("count : ", count)
      fmt.println("a: ", a)
      fmt.println("b: ", b)
  }

  >>> go run main.go
      Enter a sting and a number: Shounak yes
      count : 1
      error: expected integer
      a: Shounak
      b: 0

find type of variable

  1. %T format specifier

  2. reflect.TypeOf function from the reflect package

using %T

main.go

 package main
  import "fmt"

  func main() {
       var grades int = 42
       var message string = "hello world"
       var isCheck bool = true
       var amount float32 = 5466.54

       fmt.Printf("variable grades = %v is of type %T \n", grades, grades)
       fmt.Printf("variable message = '%v' is of type %T \n", message, message)
       fmt.Printf("variable isCheck = '%v' is of type %T \n", isCheck, isCheck)
       fmt.Printf("variable amount = %v is of type %T \n", amount, amount)
  }

  >>> go run main.go
  variable grades = 42 is of type int
  variable message = 'hello world' is of type string
  variable isCheck = 'true' is of type bool
  variable amount = 5466.54 is of type float32

using reflect.TypeOf()

main.go

package main
  import (
  "fmt"
  "reflect"
  )

  func main () {
        fmt.printf("Type: %v \n", reflect.TypeOf(1000))
        fmt.printf("Type: %v \n", reflect.TypeOf("Shounak"))
        fmt.printf("Type: %v \n", reflect.TypeOf(46.0))
        fmt.printf("Type: %v \n", reflect.TypeOf(true))

  }

  >>> go run main.go
      Type: int
      Type: string
      Type: float64
      Type: bool

Declare with variables

main.go

package main
  import (
  "fmt"
  "reflect"
  )

  func main () {
        var grades int = 42
        var message string = "hello world"
        fmt.Printf("variable grades=%v is of type %v \n", grades, reflect.TypeOf(grades))
        fmt.Printf("variable message='%v' is of type %v \n", message, reflect.TypeOf(message))

  }

  >>> go run main.go
      variable grades = 42 is of type int
      variable message = 'hello world' is of type string

Converting between data types

Type Casting

  1. The process of converting one dats type to another is known as Type Casting.

  2. Data Types can be converted to other data types, but this does bot not gurantee that the value of the varibale will remian intact.

integer to float

main.go

 package main
  import "fmt"

  fucn main() {
        vat i int = 90
        var f floatb64 = float64(i)
        fmt.Printf("%.2f\n",f)
  }

  >>> go run main.go
  90.00

float to integer

main.go

 package main
  import "fmt"

  fucn main() {
        var f float64 = 45.89
        var i int = int(f)
        fmt.Printf("%v\n",i)
  }

  >>> go run main.go
  45

strconv package

  1. Itoa()

  2. converts integer to string

  3. return one value-string froma with the given integer

main.go

  package main
  import (
  "fmt"
  "strconv"

  fucn main() {
        var i itn = 42
        var s string = strconv.Itoa(i) //convert int to string
        fmt.Printf("%q",s)
  }

  >>> go run main.go
  "42"
  1. Atoi()

  2. converts string to integer

  3. returns two values-the corresponding integer, error(if any).

string to integer

main.go

  package main
  import (
  "fmt"
  "strconv"

  fucn main() {
        var s string = "200"
        i, err := strconv.Atoi(s)
        fmt.Printf("%v, %T \n", i, i)
        fmt.Printf("%v, %T", err, err)
  }

  >>> go run main.go
  200, int
  ,

main.go

package main
  import (
  "fmt"
  "strconv"

  fucn main() {
        var s string = "200abc"
        i, err := strconv.Atoi(s)
        fmt.Printf("%v, %T \n", i, i)
        fmt.Printf("%v, %T", err, err)
  }

  >>> go run main.go
  0, int
  strconv.Atoi: parsing "200a": invalid syntax, *strconv.Numerror

Constants

Constants as the name state, they are varaiables whos values ones initialized cannot be modified.

Syntax:

 const      =

Untyped constant

  1. constants are untyped unless they are explicitly given a type at declaration.

  2. allow for flexibility

  const age = 12
  const h_name, h_age = "Shounak", 12

Typed constant

  1. constants are typed when you explicitly specify the type in the declaration.

  2. flexibility that comes with untyped constants is lost

  const name string = "Shounak Khulape"
  const age int = 12

Understanding constant

main.go

package main
  import "fmt"

  func main() {
        const name = "Shounak Khualpe"
        const is_muggle = false
        const age =  12

        fmt.Printf("%v: %T \n", name, name)
        fmt.Printf("%v: %T \n", is_muggle, is_muggle)
        fmt.Printf("%v: %T", age, age)
  }
  >>> go run main.go
  Shounak Khulape: string
  false: bool
  12: int

Core concept of constant once initialize cannot change once change cause runtime error

package main
  import "fmt"

  func main() {
        const name = "Shounak Khualpe"
        name = "Abc Def"

        fmt.Printf("%v: %T \n", name, name)
  }
  >>> go run main.go
  Error: cannot assign to name (declared const)

You cannot declare constant and not initialize it a value and will try to assign a value later on

package main
  import "fmt"

  func main() {
        const name
        name = "Shounak Khualpe"
        fmt.Printf("%v: %T \n", name, name)
  }
  >>> go run main.go
  missing value in const declaration, undefined: name

Short hand variable assignment operator

  package main
  import "fmt"

  func main() {
        const name := "Shounak Khualpe"
        fmt.Printf("%v: %T \n", name, name)
  }
  >>> go run main.go
  Error: syntax error: unexpected :=, expecting =

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

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

Thank you and Happy Learning!👏