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.
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.
Int variables in Go can be defined using the var
keyword or by type inference.
var x int = 42
y := 27
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
Int values can be compared using relational operators.
fmt.Println(x > y)
fmt.Println(x < y)
fmt.Println(x == y)
We can define and use int variables in Go to represent integer values.
For example,
x
and assign it a value.y
using type inference and assign it a value.package main
import "fmt"
func main() {
var x int = 42
y := 27
fmt.Println(x)
fmt.Println(y)
}
42 27
We can perform arithmetic operations on int values in Go.
For example,
x
and y
.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)
}
Sum: 69 Difference: 15 Product: 1134 Quotient: 1
We can compare int values in Go using relational operators.
For example,
x
and y
with different values.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
}
true false false
We can pass int values to functions and return int values from functions in Go.
For example,
add
that takes two int parameters and returns their sum.package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
result := add(10, 15)
fmt.Println(result)
}
25