2.1 Variables and Constants
Introduction
Variables and constants are fundamental concepts in any programming language, including Go. Variables store data that can change over time, while constants hold values that cannot be modified after they are defined. Understanding how to declare, initialize, and use variables and constants is essential for writing efficient and clear Go programs. In this chapter, we will explore how to declare variables, work with different types of variables, and understand the role of constants in Go.
Declaring Variables in Go
Go provides several ways to declare variables, depending on whether you want to specify the type explicitly or allow Go to infer it for you.
1. Using the var
Keyword
The most explicit way to declare a variable in Go is by using the var
keyword. You can declare a variable with or without an initial value.
var
is the keyword to declare a variable.name
is the variable name.string
is the type of the variable (in this case, a string)."Alice"
is the initial value assigned to the variable.
Multiple variable declarations:You can declare multiple variables at once using a single var
statement.
var x, y int = 10, 20
var a, b = 1.5, "hello"
In the first line, both x
and y
are declared as int
and initialized to 10
and 20
, respectively. In the second line, a
and b
are initialized with inferred types (float64
and string
).
Declaration without an initial value:You can declare a variable without initializing it right away. In this case, Go assigns a zero value to the variable (default value for the type).
var age int
Here, age
is an integer variable that has the default zero value of 0
.
Declaration with an initial value:
var name string = "Alice"
In this example:
2. Short Variable Declaration (:=
)
Go allows you to declare and initialize variables in a shorthand form using the :=
syntax. This method infers the variable type based on the initial value provided and is commonly used inside functions.
- Limitations of
:=
:- This method can only be used within functions. It cannot be used for global variables.
- You cannot omit the initial value when using
:=
, as Go needs the value to infer the type.
Example:
name := "Alice"
age := 25
In this example, the name
variable is inferred to be of type string
, and age
is inferred to be of type int
.
Variable Types in Go
Go is a statically typed language, meaning that the type of a variable is determined at compile time. Some commonly used types include:
Basic Types:
- Integer types:
int
: Default integer type, architecture-dependent (typically 32-bit or 64-bit).int8
,int16
,int32
,int64
: Signed integers with specific bit sizes.uint
,uint8
,uint16
,uint32
,uint64
: Unsigned integers.
- Floating-point types:
float32
,float64
: Floating-point numbers, wherefloat64
is the default type for decimal numbers.
- Boolean:
bool
: Representstrue
orfalse
.
- String:
string
: A sequence of characters.
Example of Declaring Variables with Different Types:
var x int = 10
var pi float64 = 3.14159
var isAvailable bool = true
var greeting string = "Hello, World!"
Default Zero Values:
If you declare a variable without initializing it, Go assigns a default zero value based on the variable's type:
- For numeric types, the default is
0
. - For
bool
, the default isfalse
. - For
string
, the default is an empty string (""
).
var x int // x is 0
var y bool // y is false
var z string // z is ""
Constants in Go
Constants are similar to variables but cannot be changed once they are set. In Go, constants are declared using the const
keyword, and they must be assigned a value at the time of declaration.
1. Declaring Constants
Type inference in constants:Like variables, Go can infer the type of constants if it's not explicitly specified.
const name = "Alice"
Here, name
is a constant of inferred type string
.
Basic constant declaration:
const pi float64 = 3.14159
In this example, pi
is a constant of type float64
and holds the value 3.14159
.
2. Multiple Constants Declaration
You can declare multiple constants at once using a grouped const
block:
const (
pi = 3.14159
e = 2.71828
isTrue = true
)
3. Untyped Constants
Go allows constants to be untyped, meaning they can take on a different type depending on how they are used.
const pi = 3.14159
Here, pi
is an untyped constant and can be used as a float32
, float64
, or even as an integer when used in a context that requires it.
4. Benefits of Constants
- Readability: Constants give your code meaningful names for values that don’t change, improving readability.
- Maintainability: If a constant value needs to be changed, it can be modified in one place without needing to update multiple parts of the code.
- Performance: Constants can be evaluated at compile time, improving the overall performance of your program.
Examples of Variables and Constants
Let’s look at an example of how variables and constants can be used in a Go program:
package main
import "fmt"
func main() {
// Declaring variables
var name string = "Alice"
age := 25
// Declaring constants
const pi = 3.14159
const city string = "New York"
// Using variables and constants
fmt.Println("Name:", name)
fmt.Println("Age:", age)
fmt.Println("Pi:", pi)
fmt.Println("City:", city)
// Changing variable value
name = "Bob"
fmt.Println("Updated Name:", name)
// Uncommenting the following line will cause an error because constants cannot be changed:
// pi = 3.14
}
Output:
Name: Alice
Age: 25
Pi: 3.14159
City: New York
Updated Name: Bob
In this example:
- We declare and initialize variables
name
andage
, and constantspi
andcity
. - The value of the variable
name
is updated, but constants likepi
cannot be modified after declaration.
Conclusion
In this chapter, we learned how to declare and use variables and constants in Go. We explored the different ways to declare variables, how type inference works, and the default zero values for variables. We also discussed the benefits of using constants in Go programs. In the next chapter, we will dive deeper into data types and operations you can perform on variables and constants.