Go Constants 🎯

beginner
5 min

Go Constants 🎯

Welcome to our deep dive into Go Constants! In this lesson, we'll explore the fascinating world of constants in Go - a crucial concept for every Go developer. Let's get started!

What are Constants? 📝

In simple terms, a constant is a named value that cannot be changed during the execution of a program. Think of it as an unchangeable variable.

Why are constants important? They help improve code readability, reduce errors, and make it easier to maintain your programs.

Declaring Constants 💡

Declaring a constant in Go is straightforward. Here's how to do it:

go
const name string = "MyConstant"

In the above example:

  • const is a keyword indicating we're declaring a constant.
  • name is the identifier for the constant.
  • string is the type of the constant (more on types later).
  • "MyConstant" is the value of the constant.

Constants Types 📝

Go supports several types of constants:

  1. bool: Boolean constants can only have the values true or false.
  2. int: Integer constants can be of type int8, int16, int32, int64, uint8, uint16, uint32, or uint64.
  3. float32 and float64: These are used for floating-point numbers.
  4. string: Used for string literals.
  5. rune: A type that represents a Unicode code point (similar to an int32).

Constants in Action 💡

Now, let's see a practical example:

go
package main import "fmt" const pi float64 = 3.141592653589793 const hello string = "Hello, World!" func main() { fmt.Println("The value of pi is:", pi) fmt.Println(hello) }

In this example, we've declared two constants: pi and hello. pi is a floating-point constant, and hello is a string constant. We then print their values using the fmt.Println() function.

Constants and Constants Values 💡

It's important to understand the difference between a constant and its value. The constant name pi in our example is a reference to the constant's value 3.141592653589793.

Constants and Variables 📝

While constants and variables share some similarities (like names and types), there are some key differences:

  1. Variables can be reassigned, while constants cannot.
  2. Constants must be initialized at the time of declaration, while variables can be initialized later.
  3. Constants are implicitly const, while variables need to be declared with a specific type.

Constants and Values 💡

Go evaluates constant expressions when the program is compiled, not at runtime. This means that you can't use variables or functions inside constant expressions.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What is a constant in Go?

That's it for our Go Constants lesson! As you practice, you'll find that constants can make your code more efficient, readable, and less prone to errors. Happy coding! 🎉