int in Go
In this tutorial, we will learn about the int data type in Go. We will cover the basics of defining and using int values, including how to perform arithmetic operations and compare integers.
Understanding the Int Data Type in Go
The int
data type in Go is used to represent integer values. The size of an int
is platform-dependent, typically 32 or 64 bits.
Defining an Int Variable
Int variables in Go can be defined using the var
keyword or by type inference.
var x int = 42
y := 27
Performing Arithmetic Operations
Arithmetic operations such as addition, subtraction, multiplication, and division can be performed on int values.
sum := x + y
difference := x - y
product := x * y
quotient := x / y
Comparing Int Values
Int values can be compared using relational operators.
fmt.Println(x > y)
fmt.Println(x < y)
fmt.Println(x == y)
Example 1: Defining and using Int Variables
We can define and use int variables in Go to represent integer values.
For example,
- Define an int variable named
x
and assign it a value. - Define another int variable named
y
using type inference and assign it a value. - Print the values of both int variables to the console.
Go Program
package main
import "fmt"
func main() {
var x int = 42
y := 27
fmt.Println(x)
fmt.Println(y)
}
Output
42 27
Example 2: Performing Arithmetic Operations
We can perform arithmetic operations on int values in Go.
For example,
- Define two int variables named
x
andy
. - Perform addition, subtraction, multiplication, and division on these int values.
- Print the results of these operations to the console.
Go Program
package main
import "fmt"
func main() {
x := 42
y := 27
sum := x + y
difference := x - y
product := x * y
quotient := x / y
fmt.Println("Sum:", sum)
fmt.Println("Difference:", difference)
fmt.Println("Product:", product)
fmt.Println("Quotient:", quotient)
}
Output
Sum: 69 Difference: 15 Product: 1134 Quotient: 1
Example 3: Comparing Int Values
We can compare int values in Go using relational operators.
For example,
- Define two int variables named
x
andy
with different values. - Use relational operators to compare the int values and print the results to the console.
Go Program
package main
import "fmt"
func main() {
x := 42
y := 27
fmt.Println(x > y) // true
fmt.Println(x < y) // false
fmt.Println(x == y) // false
}
Output
true false false
Example 4: Using Int in a Function
We can pass int values to functions and return int values from functions in Go.
For example,
- Define a function named
add
that takes two int parameters and returns their sum. - Call the function with int arguments and print the result to the console.
Go Program
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
result := add(10, 15)
fmt.Println(result)
}
Output
25