All data types in Golang with examples #1

All data types in Golang with examples #1

Play this article

Golang is a statically typed programming language meaning each variable has a type. Go has several built-in types that we will look into in this article. Data types in Go can be categorized into two types

  1. Basic Types

  2. Composite Types

Go has a range of basic data types that can be used to represent different kinds of values. Here is a list of the basic types in Go, along with examples of how they can be used:

  • bool: a boolean type that represents a true/false value. Example: var b bool = true

  • string: a string type that represents a sequence of Unicode characters. Example: var s string = "Hello, world!"

  • int: an integer type that represents a whole number. Go has several integer types, including int8, int16, int32, int64, and others. Example: var i int = 42

  • float: a floating-point type that represents a number with a decimal point. Go has two floating-point types, float32 and float64. Example: var f float64 = 3.14

  • complex: a complex number type that represents a number with both a real and an imaginary component. Go has two complex number types, complex64 and complex128. Example: var c complex128 = 3 + 4i

Here is an example of using these basic types in Go:

package main

import "fmt"

func main() {
    // Declare variables of different basic types
    var b bool = true
    var s string = "Hello, world!"
    var i int = 42
    var f float64 = 3.14
    var c complex128 = 3 + 4i

    // Print the variables
    fmt.Println(b)
    fmt.Println(s)
    fmt.Println(i)
    fmt.Println(f)
    fmt.Println(c)
}
true
Hello, world!
42
3.14
(3+4i)

Composite types in Golang are types that are made up of other types. They are used to group multiple values together and can be used to represent more complex data structures.

There are three main composite types in Golang: arrays, slices, and maps.

Arrays are fixed-length collections of items of the same type. For example:

var a [3]int
a[0] = 1
a[1] = 2
a[2] = 3
fmt.Println(a) // [1 2 3]

Slices are dynamic-length collections of items of the same type. They are built on top of arrays and can be created using the "make" function. For example:

s := make([]int, 5)
s[0] = 1
s[1] = 2
s[2] = 3
s[3] = 4
s[4] = 5
fmt.Println(s) // [1 2 3 4 5]

Maps are key-value pairs where the keys are unique. They are used to store values that can be retrieved by a unique key. For example:

m := make(map[string]int)
m["one"] = 1
m["two"] = 2
m["three"] = 3
fmt.Println(m["one"]) // 1

Composite types in Golang are useful for storing and organizing data in a structured way and can be used to represent more complex data structures such as linked lists or trees.