Day 2: Mastering Variables and Constants in Go

Venkat Annangi
Venkat Annangi
23/09/2024 15:39 2 min read 38 views
#golang #108 days of golang

Day 2: Comprehensive Guide to Variables and Constants in Go

Understanding variables and constants is essential in Go. Today, we’ll explore different ways to declare and initialize variables, discuss Go’s strong typing system, and learn about constants.

Step 1: Variable Declaration

Go offers two ways to declare variables: using the var keyword or shorthand := syntax:

Using var

var x int = 10
var name string = "John"

Explicit type declaration helps when you want to be specific about the data type.

Using Shorthand Declaration

The shorthand declaration uses := which infers the type based on the initial value:

x := 10
name := "John"

Shorthand declarations are more concise and commonly used for local variables.

Step 2: Zero Values

Go initializes variables to their "zero values" if no value is provided:

  • int zero value is 0
  • string zero value is "" (empty string)
  • bool zero value is false

Example:

var age int
fmt.Println(age)  // Outputs: 0

Step 3: Constants

Constants are declared using the const keyword and cannot change once set. They’re ideal for fixed values like Pi:

const Pi = 3.14159

Step 4: Typed and Untyped Constants

Constants in Go can be typed or untyped. Untyped constants are more flexible as they can be used in expressions with different types:

const a = 10  // Untyped
const b int = 20  // Typed

Step 5: Practical Exercise

Write a program that calculates the area of a circle using a constant for Pi:

package main

import "fmt"

func main() {
   const Pi = 3.14159
   radius := 5.0
   area := Pi * radius * radius
   fmt.Printf("Area of the circle: %.2f\n", area)
}

This program demonstrates constants and basic arithmetic operations.

Comments