Algorithm


In the Go programming language, variables and constants are fundamental components used to store and manage data. Here's an overview of how you declare and use variables and constants in Go:

Variables:

Variables are used to store and manage data. They must be declared before use.

Declaration:

go
var variableName dataType

Example:

go
var age int

Initialization:

go
variableName = value

Example:

go
age = 25

Declaration and Initialization (short syntax):

go
variableName := value

Example:

go
name := "John" 

Constants:

Constants are values that don't change during the program's execution. They are declared using the const keyword.

Declaration:

go
const constantName dataType = value

Example:

go
const pi float64 = 3.14159

Constants can also be declared without specifying the data type (the type will be inferred from the value):

go
const pi = 3.14159
 

Multiple Variable Declaration:

You can declare multiple variables at once:

go
var (
    firstName string
    lastName  string
    age       int
)
 

Blank Identifier:

The _ (underscore) is the blank identifier and can be used to discard values.

go
_, err := someFunctionReturningTwoValues()

 

Code Examples

#1 Code Example with Golang Programming

Code - Golang Programming

package main

import "fmt"

func main() {
    // Variable declaration and initialization
    var message string
    message = "Hello, Go!"
    fmt.Println(message)

    // Short variable declaration
    age := 30
    fmt.Println("Age:", age)

    // Constant declaration
    const pi = 3.14159
    fmt.Println("Value of pi:", pi)
}
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Go Variables and Constants- Go Lang Programming