1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Constant In Golang 2019

Discussion in 'Programming' started by Sagar Jaybhay, Dec 10, 2019.

Tags:
  1. Sagar Jaybhay

    Sagar Jaybhay New Member

    Joined:
    Jan 28, 2019
    Messages:
    27
    Likes Received:
    15
    Trophy Points:
    3
    Gender:
    Male
    Occupation:
    Sr. Software Developer
    Location:
    Pune
    Home Page:
    In the below program we create the variable x and assign value 10 after this we again assign value 12 to the same variable x and we print this on the console which is working fine. By using this you will know we can change the value of variable anytime in our program.



    Code:
    package main
    
    import (
        "fmt"
    
        "./utilitypackage"
    )
    
    func main() {
    
        //fmt.Println(utilitypackage.Reverse("sagar"))
        //utilitypackage.CreateDataTypes()
    
        var x = 10
        fmt.Println("val is x", x)
    
        x = 12
        fmt.Println("changed val is x", x)
    
        fmt.Println("\n called in main ", utilitypackage.Name)
    
    }
    
    Geral Variable In Golang.png


    Now we will create constant and check what will happen to see below image :


    Constant In Golang.png


    Below is the program for that

    Code:
    
    package main
    
    import (
       "fmt"
    
       "./utilitypackage"
    )
    
    func main() {
    
       //fmt.Println(utilitypackage.Reverse("sagar"))
       //utilitypackage.CreateDataTypes()
    
       const x = 10
       fmt.Println("val is x", x)
    
       x = 12
       fmt.Println("changed val is x", x)
    
       fmt.Println("\n called in main ", utilitypackage.Name)
    
    }
    
    
    
    



    When you declared a constant in your program you can’t change the value of this variable again in your program. If you try to change the value of this it will throw an error.

    Point to remember when you declared a constant you need to assign value to that variable at the time of declaration else it will throw an error.

    See below image

    Constant In Golang.png



    Different way’s to declare constant variables in golang
    Code:
    package main
    
    import "fmt"
    
    const b string = "sagar jaybhay"
    const a = 42
    
    const (
       v = iota
       j = iota * 10
       k = iota * 10
    )
    
    func main() {
    
       const aa = "sagar"
       fmt.Println("hello brother")
       println(v)
       println(j)
       println(k)
    }
    [/SIZE]
    

    Different Ways to declare Constant with iota.png
     

    Attached Files:

Share This Page