Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

 Data Types in Go

6. Data Types in Go

1. Numeric Types:

Go supports various numeric types for integers and floating-point numbers.

  • 'int': Represents signed integers of various sizes (platform-dependent).
var age int = 25

 

  • 'float32','float64': Represents floating-point numbers with single and double precision.
var pi float64 = 3.14159

 

  • 'complex64', 'complex128': Represents complex numbers with single and double precision.
var z complex128 = 2 + 3i

 

2. String Type:

The 'string' type represents a sequence of characters.

var message string = "Hello, Go!"

 

3. Boolean Type:

The'bool'type represents the two truth values, 'true'and 'false'.

var isSunny bool = true

 

4. Character Type (rune):

Characters are represented as 'rune' (Unicode code points), an alias for 'int32'.

var letter rune = 'A'

 

5. Array Types:

Arrays are fixed-size collections of elements of the same type.

var numbers [5]int = [5]int{1, 2, 3, 4, 5}

 

6. Slice Types:

Slices are dynamic-size views of an underlying array.

var colors []string = []string{"red", "green", "blue"}

 

7. Map Types:

Maps are unordered collections of key-value pairs.

var ages map[string]int = map[string]int{"Alice": 25, "Bob": 30}

 

8. Struct Types:

Structs are composite data types that group together fields of possibly different types.

type Person struct {
Name string
Age int
}
var person Person = Person{Name: "Alice", Age: 25}

 

9. Pointer Types:

Pointers store memory addresses and are used to indirectly access values.

var x int = 42
var ptr *int = &x

 

10. Function Types:

Functions can have their own types, which specify the parameter types and return type.

type MathFunc func(int, int) int

 

11. Interface Types:

Interfaces define a set of method signatures that a type must implement.

type Shape interface {
Area() float64
}

 

12. Channel Types:

Channels are used for communication between goroutines.

ch := make(chan int)

 

13. Pointer to Function Type:

Pointers can also be used with function types.

var fnPtr func(int, int) int

 

14. Type Aliases:

Type aliases allow you to create alternative names for existing types.

type Celsius float64

 

Understanding the various data types in Go is essential for writing correct and efficient code. Selecting the appropriate data type for your variables and functions ensures proper memory usage and behavior of your programs.