1 Replies - 134 Views - Last Post: 10 December 2019 - 12:13 PM Rate Topic: -----

#1 Sagar-Jaybhay   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 18-February 19

Different ways to declare constant in golang 2019

Posted 10 December 2019 - 11:35 AM

Constant in Go language / Golang

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.

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)

}





Posted Image



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


Posted Image





Below is the program for Constant



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

Posted Image



Different way’s to declare constant variables in golang


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)
}





Is This A Good Question/Topic? 0
  • +

Replies To: Different ways to declare constant in golang 2019

#2 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15506
  • View blog
  • Posts: 62,082
  • Joined: 12-June 08

Re: Different ways to declare constant in golang 2019

Posted 10 December 2019 - 12:13 PM

This is not an 'introduce yourself' post. Moving to 'other languages'

It's also frowned upon to copy/dump stuff from your site.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1