Go Variables and Constants
Variables and constants are an essential part of any programming language, including Go. Here's how you can define and use them in your Go programs:
Variables
A variable is a named storage location that holds a value of a particular type. In Go, you can define a variable using the var
keyword, followed by the variable name, and the type of the variable. Here's an example:
var x int // declare a variable of type int x = 5 // assign a value to the variable
Alternatively, you can use the short variable declaration syntax (:=
) to declare and initialize a variable in one line:
y := "Hello" // declare and initialize a variable of type string
Go also supports multiple variable declaration in a single line, separated by commas:
var a, b, c int // declare three variables of type int a, b, c = 1, 2, 3 // assign values to the variables
You can also use the blank identifier (_
) to discard a value or to declare a variable without assigning a value to it:
_, err := fmt.Println("Hello, world!") // discard the return value of fmt.Println() var z int // declare a variable of type int without assigning a value
Constants
A constant is a value that cannot be changed during the execution of a program. In Go, you can define a constant using the const
keyword, followed by the constant name and value. Here's an example:
const Pi = 3.14159 // define a constant named Pi
Go also supports the same syntax for multiple constant declaration in a single line, separated by commas:
const ( Monday = 1 Tuesday = 2 Wednesday = 3 Thursday = 4 Friday = 5 Saturday = 6 Sunday = 7 )
Note that constants can only be assigned with constant expressions, which are values that can be determined at compile time. For example, you can assign the result of an arithmetic expression to a constant, but not the result of a function call.
const ( a = 1 + 2 // valid b = math.Sqrt(4.0) // invalid, math.Sqrt() is not a constant expression )
Variables and constants are fundamental concepts in Go programming that you'll use extensively in your programs.