ADVERTISEMENT
ADVERTISEMENT

Golang program to demonstrate the 'const' keyword

Here, we are going to demonstrate the 'const' keyword in Golang (Go Language)?
Submitted by Nidhi, on February 21, 2021

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

Problem Solution:

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.

Golang Basic Programs »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.