Ad space (banner)
๐ŸนGo Lessons
Lesson 19 / 68

Constants (const)

In this lesson you will learn how to declare constants with const in Go, so values that must not change are handled safely. This is for anyone searching for "Go const how to use".

The const keyword creates a constant whose value cannot be changed later. It is often declared outside any function, at package level.

The sample code defines a perfect score as a constant with const MaxScore = 100 and uses it to build a message with fmt.Printf. Constants are a basic technique for avoiding magic numbers and communicating the intent of your code.

A common stumbling block for beginners is knowing when to reach for a constant rather than a variable. Using one for a value that never changes protects you from overwriting it by mistake. Paired with iota, you can also declare a run of sequential constants neatly.

In real-world development a package-level constant can be referenced as a shared value from several files, which helps keep configuration in one place.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)