Welcome to our deep dive into Go arithmetic operators! This lesson will guide you through the world of numbers in Go, making it easy for both beginners and intermediates to understand. Let's get started!
Go supports the following basic arithmetic operators:
+ (Addition)- (Subtraction)* (Multiplication)/ (Division)% (Modulus)Let's start with addition and subtraction. Here's an example of how to add and subtract numbers in Go:
package main
import "fmt"
func main() {
x := 5
y := 3
sum := x + y // Addition
difference := x - y // Subtraction
fmt.Println("Sum:", sum)
fmt.Println("Difference:", difference)
}In this example, we define two variables x and y, and then perform addition and subtraction operations. The result is printed to the console.
Multiplication and division work in a similar way. Here's a simple example:
package main
import "fmt"
func main() {
x := 5
y := 3
product := x * y // Multiplication
quotient := x / y // Division
fmt.Println("Product:", product)
fmt.Println("Quotient:", quotient)
}In this example, we perform multiplication and division operations on the variables x and y. The result is printed to the console.
The modulus operator (%) returns the remainder of the division. Here's an example:
package main
import "fmt"
func main() {
x := 17
y := 5
remainder := x % y // Modulus
fmt.Println("Remainder:", remainder)
}In this example, we calculate the remainder when 17 is divided by 5. The result is printed to the console.
Compound assignment operators allow you to perform arithmetic operations and assign the result back to the same variable. Here are some examples:
+= (Addition and Assignment)-= (Subtraction and Assignment)*= (Multiplication and Assignment)/= (Division and Assignment)%= (Modulus and Assignment)Here's an example using the compound assignment operator:
package main
import "fmt"
func main() {
x := 5
x += 3 // x = x + 3
x -= 2 // x = x - 2
x *= 4 // x = x * 4
x /= 2 // x = x / 2
fmt.Println("x:", x)
}In this example, we perform several arithmetic operations on the variable x using compound assignment operators. The result is printed to the console.
Operator precedence determines the order in which operations are executed. In Go, operators have a specific precedence, which you should keep in mind when writing complex expressions.
For example:
package main
import "fmt"
func main() {
x := 5
y := 2
result := x * y + 3
fmt.Println("Result:", result)
}In this example, multiplication is performed before addition due to operator precedence. If you want to change the order of operations, you can use parentheses:
package main
import "fmt"
func main() {
x := 5
y := 2
result := (x * y) + 3
fmt.Println("Result:", result)
}What does the modulus operator (`%`) do in Go?
That's it for our deep dive into Go arithmetic operators! Now you have a solid understanding of basic arithmetic operations, compound assignment operators, and operator precedence. Keep practicing, and happy coding! 💡