Basic Syntax in Go: Variables and Constants, Data Types (integers, floats, strings, booleans), Operators (+, -, *, /, %)
Understanding the fundamental syntax of a programming language is the first step towards mastering it. In this section, we’ll delve into the basic syntax of Go, covering essential concepts like variables and constants, data types encompassing integers, floats, strings, and booleans, as well as operators such as addition, subtraction, multiplication, division, and modulo.
Variables and Constants
Variables and constants are integral components of any programming language, allowing us to store and manage data in our programs.
Declaring Variables
In Go, you declare a variable using the var
keyword, followed by the variable name and its data type.
var age int
age = 30
You can also initialize a variable at the time of declaration:
var name string = "Alice"
Declaring Constants
Constants are declared using the const
keyword in Go.
const pi float64 = 3.14159
Data Types
Data types in Go define the kind of value a variable can hold. Let’s explore some commonly used data types.
Integers
Integers are whole numbers, positive or negative, without a decimal point.
var num int = 42
Floats
Floats represent real numbers and have decimal points.
var pi float64 = 3.14
Strings
Strings hold a sequence of characters, enclosed within double quotes.
var message string = "Hello, Go!"
Booleans
Booleans represent true or false values.
var isGoAwesome bool = true
Operators
Operators are symbols that perform operations on variables and values.
Addition (+)
The addition operator is used to add two numbers.
var sum int = 10 + 20
Subtraction (-)
Subtraction operator subtracts the right operand from the left operand.
var difference int = 30 - 10
Multiplication (*)
Multiplication operator multiplies two numbers.
var product int = 5 * 4
Division (/)
Division operator divides the left operand by the right operand.
var quotient float64 = 25.0 / 5.0
Modulo (%)
Modulo operator gives the remainder of the division.
var remainder int = 10 % 3
Understanding these basic syntax elements – variables, constants, data types, and operators – lays a solid foundation for further exploration into Go’s capabilities. You can now start building and manipulating data in your Go programs with a clearer understanding of these essential concepts.