Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Go Programming - Data Types Tutorial

Introduction

In Go programming, data types are a crucial concept that defines the kind of data a variable can hold. Understanding data types helps you to manage memory efficiently and write more reliable code. This tutorial will cover fundamental data types in Go, including examples to illustrate their usage.

Basic Data Types

Go offers several basic data types, including:

  • Integers
  • Floating-point numbers
  • Booleans
  • Strings

Integers

Integers are whole numbers without a fractional part. Go provides various types of integers:

  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64

Here's an example of how to use integers in Go:

package main

import "fmt"

func main() {
    var a int = 10
    var b int8 = 20
    fmt.Println("a:", a)
    fmt.Println("b:", b)
}

The output will be:

a: 10
b: 20

Floating-point Numbers

Floating-point numbers are numbers with a decimal point. Go supports two types of floating-point numbers:

  • float32
  • float64

Here's an example of how to use floating-point numbers in Go:

package main

import "fmt"

func main() {
    var x float32 = 3.14
    var y float64 = 2.718
    fmt.Println("x:", x)
    fmt.Println("y:", y)
}

The output will be:

x: 3.14
y: 2.718

Booleans

Booleans represent truth values and can be either true or false. They are particularly useful in conditional statements and logical operations.

Here's an example of how to use booleans in Go:

package main

import "fmt"

func main() {
    var isTrue bool = true
    var isFalse bool = false
    fmt.Println("isTrue:", isTrue)
    fmt.Println("isFalse:", isFalse)
}

The output will be:

isTrue: true
isFalse: false

Strings

Strings are sequences of characters used to store text. In Go, strings are enclosed in double quotes (").

Here's an example of how to use strings in Go:

package main

import "fmt"

func main() {
    var greeting string = "Hello, World!"
    fmt.Println(greeting)
}

The output will be:

Hello, World!

Conclusion

In this tutorial, we covered the basic data types in Go, including integers, floating-point numbers, booleans, and strings. Understanding these data types is fundamental to writing efficient and reliable Go programs. Practice using these data types in your own programs to become more proficient in Go programming.