Q:

Golang program to demonstrate the \'const\' keyword

belongs to collection: Golang Basic Programs

0

The const keyword is used to declare a constant in Golang. The constants are declared like variables, but with the const keyword and the constant value. Following types can be declared as constants,

  • Character
  • String
  • Boolean
  • Numeric values

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will create two constants using the "const" keyword. We cannot modify the value of constants during the program.

Program/Source Code:

The source code to demonstrate the const keyword is given below. The given program is compiled and executed successfully.

// Golang program to demonstrate the "const" keyword

package main

import "fmt"

func main() {
	const str string = "India"
	const intval int = 108
	const c byte = 'x'

	//Constant value cannot modify, will generate error.
	//intval=500

	fmt.Printf("String: %s", str)
	fmt.Printf("\nValue: %d", intval)
	fmt.Printf("\ncharacter: %c", c)
}

Output:

String: India
Value: 108
character: x

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.

In the main() function, we created a string, an integer and a byte constant, which are initialized with "India", 108, 'x'. As we know that, we cannot modify the value of constants during the program. If we assign a new value to the constant then syntax error gets generated.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to demonstrate Sizeof() operator... >>
<< Golang program to calculate the area of the Rectan...