Data Types in Go
Go is a statically typed language which means the type of a variable is checked at compile time. This section will cover the various types of data that can be handled in Go. We'll look at several types, including:
- Basic types
- Composite types
- Other types
Basic Types
Numbers
In Go, there are several number types which include integers, floating point numbers, and complex numbers.
- Integers: Integer types in Go include
int
anduint
which are of 32-bits on 32-bit systems and 64-bits on 64-bit systems. There are also sized integer types likeint8
,int16
,int32
,int64
,uint8
,uint16
,uint32
,uint64
.
var i int = 10
var j int32 = 20
- Floating Point Numbers: Go has two floating point types -
float32
andfloat64
.
var f float64 = 3.14
- Complex Numbers: Go supports complex numbers of type
complex64
andcomplex128
.
var c complex64 = 1 + 2i
Boolean
A Boolean type represents two values: true
and false
var b bool = true
Strings
A string type represents a sequence of characters.
var s string = "Hello, World!"
Composite Types
Composite types in Go are arrays, slices, maps, and structs.
- Arrays: An array is a numbered sequence of elements of a single type with a fixed length.
var a [5]int
- Slices: A slice is similar to an array but it does not have a fixed length.
var s []int
- Maps: A map is an unordered collection of key-value pairs.
var m map[string]int
- Structs: A struct is a collection of fields.
type Person struct {
Name string
Age int
}
Other Types
- Pointers: A pointer holds the memory address of a value.
var p *int
- Functions: In Go, functions are first class citizens. They can be assigned to variables or passed as arguments to other functions.
func add(x int, y int) int {
return x + y
}
- Interfaces: An interface is a collection of method signatures.
type Geometry interface {
Area() float64
Perim() float64
}
Understanding the different data types in Go is fundamental to working with the language. Using the correct data type for your variables can help to make your code more efficient and easier to maintain.