Home Go Tutorial on Data Types in Go

Tutorial on Data Types in Go

In Go, data types define the kind of values that a variable can hold.

Go is a statically typed language, meaning each variable must have a specific type determined at compile time.

Go provides a wide range of built-in data types, including basic types (like integers and strings) and composite types (like arrays, structs, and maps).

In this tutorial, we’ll cover:

1. Basic Data Types

Go has several basic data types, which are grouped into categories like integers, floating-point numbers, booleans, and strings.

Integer Types

Go has signed and unsigned integer types with different sizes. The most common types are:

  • int: Platform-dependent size (usually 32 or 64 bits)
  • int8, int16, int32, int64: Signed integers with fixed sizes
  • uint8, uint16, uint32, uint64: Unsigned integers with fixed sizes
package main

import "fmt"

func main() {
    var age int = 30          // int
    var score int64 = 100      // int64
    var unsignedNum uint32 = 50 // uint32

    fmt.Println("Age:", age)
    fmt.Println("Score:", score)
    fmt.Println("Unsigned number:", unsignedNum)
}

Output:

Age: 30
Score: 100
Unsigned number: 50

Floating-Point Types

Go has two types for floating-point numbers:

  • float32: 32-bit floating-point number
  • float64: 64-bit floating-point number (more precise, and commonly used)
package main

import "fmt"

func main() {
    var price float32 = 9.99
    var weight float64 = 75.5

    fmt.Println("Price:", price)
    fmt.Println("Weight:", weight)
}

Output:

Price: 9.99
Weight: 75.5

Boolean Type

The bool type represents a boolean value, which can only be true or false.

package main

import "fmt"

func main() {
    var isActive bool = true
    var isVerified bool = false

    fmt.Println("Is Active:", isActive)
    fmt.Println("Is Verified:", isVerified)
}

Output:

Is Active: true
Is Verified: false

String Type

The string type represents a sequence of characters (text). Strings are immutable in Go, meaning their values cannot be changed once assigned.

package main

import "fmt"

func main() {
    var greeting string = "Hello, Go!"
    fmt.Println("Greeting:", greeting)

    // Multi-line string
    var message = `This is a 
multi-line string in Go.`
    fmt.Println("Message:", message)
}

Output:

Greeting: Hello, Go!
Message: This is a 
multi-line string in Go.

In this example:

  • greeting is a single-line string.
  • message is a multi-line string, using backticks (`) to span multiple lines.

2. Composite Data Types

Composite data types allow you to group multiple values together.

Arrays

An array is a fixed-size collection of elements of the same type.

package main

import "fmt"

func main() {
    var numbers = [3]int{10, 20, 30}
    fmt.Println("Numbers array:", numbers)
}

Output:

Numbers array: [10 20 30]

Slices

A slice is a dynamically-sized, flexible view into an array. Slices are commonly used in Go due to their flexibility.

package main

import "fmt"

func main() {
    var names = []string{"Alice", "Bob", "Charlie"}
    fmt.Println("Names slice:", names)

    // Adding an element to a slice
    names = append(names, "David")
    fmt.Println("Updated names slice:", names)
}

Output:

Names slice: [Alice Bob Charlie]
Updated names slice: [Alice Bob Charlie David]

In this example:

  • append() is used to add an element to a slice.

Maps

A map is a collection of key-value pairs, where each key is unique. Maps are useful for looking up values by keys.

package main

import "fmt"

func main() {
    var ages = map[string]int{
        "Alice": 30,
        "Bob":   25,
        "Carol": 35,
    }
    fmt.Println("Ages map:", ages)
}

Output:

Ages map: map[Alice:30 Bob:25 Carol:35]

Structs

A struct is a collection of fields that group different types of data together. Structs are commonly used to define custom data types in Go.

package main

import "fmt"

// Define a struct
type Person struct {
    Name string
    Age  int
    City string
}

func main() {
    // Initialize a struct
    var person = Person{
        Name: "Alice",
        Age:  30,
        City: "New York",
    }
    fmt.Println("Person struct:", person)
}

Output:

Person struct: {Alice 30 New York}

In this example:

  • Person is a struct with three fields: Name, Age, and City.

3. Type Inference and Type Conversion

Type Inference

Go can infer the type of a variable based on its assigned value, allowing you to declare variables without explicitly specifying the type.

package main

import "fmt"

func main() {
    count := 10           // inferred as int
    price := 19.99        // inferred as float64
    isMember := true      // inferred as bool
    message := "Hello!"   // inferred as string

    fmt.Println("Count:", count)
    fmt.Println("Price:", price)
    fmt.Println("Is Member:", isMember)
    fmt.Println("Message:", message)
}

Output:

Count: 10
Price: 19.99
Is Member: true
Message: Hello!

In this example:

  • The types of count, price, isMember, and message are inferred from their values.

Type Conversion

To convert a value from one type to another, use Go’s built-in conversion syntax.

package main

import "fmt"

func main() {
    var a int = 10
    var b float64 = float64(a) // Convert int to float64
    var c int = int(b)          // Convert float64 back to int

    fmt.Println("Integer:", a)
    fmt.Println("Converted to float64:", b)
    fmt.Println("Converted back to int:", c)
}

Output:

Integer: 10
Converted to float64: 10
Converted back to int: 10

In this example:

  • float64(a) converts a from int to float64.
  • int(b) converts b back from float64 to int.

Note: Type conversion is explicit in Go, meaning you have to manually specify the target type.

4. Best Practices for Data Types in Go

a) Use Type Inference Where Appropriate

Use type inference when the type is clear from the assigned value. This helps make your code cleaner.

count := 10     // inferred as int
message := "Hi" // inferred as string

b) Use structs for Custom Data Types

Use structs to group related fields together, especially when working with more complex data.

type Car struct {
    Make  string
    Model string
    Year  int
}

c) Avoid Using Unnecessary Conversions

Avoid unnecessary type conversions, as this can make the code less readable and less efficient.

d) Use Descriptive Variable Names

Always use meaningful and descriptive names for variables, especially for types like structs and maps.

var employeeSalaries = map[string]float64{
    "Alice": 60000,
    "Bob":   75000,
}

Summary

In this tutorial, we covered the basics of data types in Go:

  1. Basic Data Types: Integers, floating-point numbers, booleans, and strings.
  2. Composite Data Types: Arrays, slices, maps, and structs.
  3. Type Inference and Type Conversion: Using Go’s type inference and performing explicit type conversions.
  4. Best Practices for Data Types in Go: Writing clean, maintainable code by using appropriate types and naming conventions.

Understanding data types is fundamental in Go, as it ensures type safety and enables you to work effectively with the language's rich type system.

 

You may also like