Go Tutorials

Go Programs

Go int


Go int

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)


Defining and using Int Variables

We can define and use int variables in Go to represent integer values.

For example,

  1. Define an int variable named x and assign it a value.
  2. Define another int variable named y using type inference and assign it a value.
  3. 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


Performing Arithmetic Operations

We can perform arithmetic operations on int values in Go.

For example,

  1. Define two int variables named x and y.
  2. Perform addition, subtraction, multiplication, and division on these int values.
  3. 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


Comparing Int Values

We can compare int values in Go using relational operators.

For example,

  1. Define two int variables named x and y with different values.
  2. 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


Using Int in a Function

We can pass int values to functions and return int values from functions in Go.

For example,

  1. Define a function named add that takes two int parameters and returns their sum.
  2. 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