Table of Contents | |
Understanding Go DataTypes
Go datatypes specify the kind of values that variables can store. Every variable in Go has an associated type. This type determines the size and layout of the variable’s memory. It also determines the range of values that can be stored. Furthermore, datatypes decide the operations that can be performed on the variable. Using appropriate Go datatypes ensures type safety and helps write correct code.
List of Different Go DataTypes
Basic Types
Basic types in Go are the fundamental data types provided by the language. These include numbers, booleans, and strings. These types represent the simplest forms of data. You can declare variables like integers, floating-point numbers, true/false values, and character strings. These are the building blocks for more complex data structures.
- Numbers: Used to represent numeric values.
- Booleans: Used to represent truth values (
true
orfalse
). - Strings: Used to represent sequences of characters (text).
Numbers
Numeric types are used to deal with numbers. There are different types of signed, unsigned, and floating numbers.
Integers
Integers in Go are whole numbers without any fractional part. Go provides both signed and unsigned integers. Signed integers can be positive, negative, or zero. Unsigned integers are always non-negative. Go has int
, int8
, int16
, int32
, int64
, uint
, uint8
, uint16
, uint32
, uint64
.
Syntax
var variableName int // Or int8, int16, etc.
Explanation
var
keyword used for declaration.variableName
is name for the variable.int
(or a specific size) specifies the type.
Example
package main
import "fmt"
func main() {
var a int = 10
var b int8 = -5
fmt.Println(a, b)
}
Explanation
var a int = 10
declares an integer variable.var b int8 = -5
declares a signed 8-bit.fmt.Println(a, b)
prints values.
Output
10 -5
Floating-Point Numbers
Floating-point numbers in Go represent numbers with a decimal point. They can also represent very large or very small numbers. Go offers two floating-point types: float32
and float64
. float64
provides more precision and is generally preferred. You should use these for any real numbers.
Syntax
var variableName float64 // Or float32
Explanation
var
declares the variable.variableName
is name assigned for variable.float64
(orfloat32
) specifies type.
Example
package main
import "fmt"
func main() {
var price float64 = 99.99
var discount float32 = 10.5
fmt.Println(price, discount)
}
Explanation
var price float64 = 99.99
declares 64-bit.var discount float32 = 10.5
declares 32-bit.fmt.Println(price, discount)
displays values.
Output
99.99 10.5
Booleans
Booleans in Go represent truth values. A boolean variable can have one of two values: true
or false
. You use booleans in control structures like if
statements and loops. They are essential for making decisions in your code.
Syntax
var variableName bool
Explanation
var
keyword declares variable.variableName
is identifier given to variable.bool
specifies the boolean type.
Example
package main
import "fmt"
func main() {
var isReady bool = true
var isComplete bool = false
fmt.Println(isReady, isComplete)
}
Explanation
var isReady bool = true
declare and assign.var isComplete bool = false
declares boolean.fmt.Println(isReady, isComplete)
prints values.
Output
true false
Strings
Strings in Go are sequences of characters. They are immutable, meaning you cannot change their contents after creation. You define strings using double quotes (“). Go provides many built-in functions for string manipulation. You can concatenate strings and get their length.
Syntax
var variableName string
Explanation
var
keyword declares variable.variableName
is identifier given to string.string
specifies the string type.
Example
package main
import "fmt"
func main() {
var greeting string = "Hello"
var name string = "Go"
fmt.Println(greeting, name)
}
Explanation
var greeting string = "Hello"
declares string.var name string = "Go"
also declares string.fmt.Println(greeting, name)
prints string values.
Output
Hello Go
Aggregate Types
Aggregate types in Go combine multiple elements of other types into a single unit. The two main aggregate types are arrays and structs. These types allow you to group related data. This makes your code more organized.
- Arrays: Fixed-size collections of elements of the same data type.
- Structs: Collections of fields (variables) that can be of different data types.
Arrays
Arrays in Go are fixed-size sequences of elements of the same type. The size of an array is part of its type. This means that arrays cannot be resized. You declare an array by specifying the element type and the number of elements. The array is a useful collection.
Syntax
var arrayName [size]dataType
Explanation
var
keyword declares the array.arrayName
is the identifier you assign.[size]
specifies the number of elements.dataType
indicates the type of elements.
Example
package main
import "fmt"
func main() {
var numbers [3]int
numbers[0] = 1
numbers[1] = 2
numbers[2] = 3
fmt.Println(numbers)
}
Explanation
var numbers [3]int
declares an array.numbers[0] = 1
,numbers[1] = 2
,numbers[2] = 3
assigns.fmt.Println(numbers)
prints the array.
Output
[1 2 3]
Structs
Structs in Go are composite data types that group variables of different types under a single name. You can think of a struct as a collection of fields. Each field has its name and type. Structs are useful for representing complex data structures.
Syntax
type structName struct {
fieldName1 dataType1
fieldName2 dataType2
// ...
}
Explanation
type
keyword defines a new struct type.structName
is identifier for struct.fieldName1
,fieldName2
, etc., members.dataType1
,dataType2
, types of fields.
Example
package main
import "fmt"
type Person struct {
FirstName string
LastName string
Age int
}
func main() {
var p Person
p.FirstName = "John"
p.LastName = "Doe"
p.Age = 30
fmt.Println(p)
}
Explanation
type Person struct { ... }
defines struct.FirstName
,LastName
,Age
are struct.var p Person
declares variable typePerson
.p.FirstName = "John"
etc., assign values.fmt.Println(p)
prints the struct.
Output
{John Doe 30}
Reference Types
Reference types in Go refer to other values indirectly. Instead of holding the data directly, they hold a memory address that points to the data. Common reference types include pointers, slices, maps, functions, and channels. These types are essential for dynamic data.
- Pointers: Variables that hold the memory address of another variable.
- Slices: Dynamically-sized, flexible views into an underlying array.
- Maps: Unordered collections of key-value pairs.
- Functions: Blocks of code that can be called and reused.
- Channels: Used for communication and synchronization between goroutines.
Pointers
Pointers in Go are variables that store the memory address of another variable. You declare a pointer using the * operator followed by the type of the variable it points to. To get the memory address of a variable, you use the & operator.
Syntax
var pointerName *dataType
Explanation
var
declares a pointer variable.pointerName
is the identifier assigned.*dataType
indicates type it points.
Example
package main
import "fmt"
func main() {
var x int = 10
var p *int
p = &x
fmt.Println(*p)
}
Explanation
var x int = 10
declares an integer variable.var p *int
declares pointer to an integer.p = &x
assigns the address ofx
top
.fmt.Println(*p)
dereferencesp
value.
Output
10
Slices
Slices in Go are dynamically sized, flexible views into the elements of an array. Unlike arrays, slices can grow or shrink. A slice does not store any data itself; it just describes a section of an underlying array. Slices are used for list-type data structures.
Syntax
var sliceName []dataType
Explanation
var
keyword declares the slice.sliceName
is identifier given to slice.[]dataType
indicates a slice ofdataType
.
Example
package main
import "fmt"
func main() {
var numbers []int
numbers = append(numbers, 1)
numbers = append(numbers, 2)
fmt.Println(numbers)
}
Explanation
var numbers []int
declares an integer slice.numbers = append(numbers, 1)
adds element.numbers = append(numbers, 2)
adds element.fmt.Println(numbers)
prints slice content.
Output
[1 2]
Maps
Maps in Go are unordered collections of key-value pairs. Each key in a map is unique. Keys are used to look up the associated values quickly. You can think of a map like a dictionary. Maps are very powerful and commonly used.
Syntax
var mapName map[keyType]valueType
Explanation
var
keyword declares map variable.mapName
is the identifier you choose.map[keyType]valueType
defines key & value.
Example
package main
import "fmt"
func main() {
var ages map[string]int
ages = make(map[string]int)
ages["Alice"] = 30
ages["Bob"] = 25
fmt.Println(ages)
}
Explanation
var ages map[string]int
declares a map.ages = make(map[string]int)
initializes.ages["Alice"] = 30
adds key-value pairs.fmt.Println(ages)
prints the map.
Output
map[Alice:30 Bob:25]
Functions
Functions in Go are also considered a type. This means you can assign functions to variables, pass functions as arguments to other functions, and return functions from other functions. This concept is known as first-class functions. It enables powerful programming techniques.
Syntax
var functionVariable func(parameterTypes) returnType
Explanation
var
declares a variable to hold function.func(parameterTypes) returnType
is signature.- Assign compatible function to variable.
Example
package main
import "fmt"
func add(x int, y int) int {
return x + y
}
func main() {
var operation func(int, int) int
operation = add
result := operation(5, 3)
fmt.Println(result)
}
Explanation
add(x int, y int) int { ... }
defines func.var operation func(int, int) int
function type.operation = add
assignsadd
tooperation
.result := operation(5, 3)
calls via variable.fmt.Println(result)
prints result.
Output
8
Channels
Channels in Go are used for communication and synchronization between goroutines. A goroutine is a lightweight, concurrent function execution. Channels provide a way to send and receive values between goroutines, making them essential for writing concurrent programs.
Syntax
var channelName chan dataType
Explanation
var
declares a channel variable.channelName
is identifier assigned.- `chan dataType
chan dataType
specifies the channel type.
Example
package main
import "fmt"
func main() {
ch := make(chan string)
go func() {
ch <- "Hello from goroutine!"
}()
message := <-ch
fmt.Println(message)
}
Explanation
ch := make(chan string)
creates a channel.go func() { ... }()
starts a goroutine.ch <- "Hello from goroutine!"
sends value.message := <-ch
receives a value fromch
.fmt.Println(message)
prints received message.
Output
Hello from goroutine!
Interface Type
The interface type in Go is a special type representing a set of method signatures. A value of interface type can hold any value that implements those methods. Interfaces enable polymorphism. They allow you to write code that can work with different types.
Syntax
type interfaceName interface {
method1(parameterTypes) returnTypes
method2(parameterTypes) returnTypes
// ...
}
Explanation
type
keyword defines an interface.interfaceName
is identifier for interface.method1
,method2
, define method signatures.- Any type implementing these is of this interface.
Example
package main
import "fmt"
type Speaker interface {
Speak() string
}
type Dog struct{}
func (d Dog) Speak() string {
return "Woof!"
}
type Cat struct{}
func (c Cat) Speak() string {
return "Meow!"
}
func main() {
var s Speaker
s = Dog{}
fmt.Println(s.Speak())
s = Cat{}
fmt.Println(s.Speak())
}
Explanation
type Speaker interface { ... }
defines.Speak() string
is the method signature.type Dog struct{}
andtype Cat struct{}
defines.(d Dog) Speak() string
and(c Cat) Speak() string
implements.var s Speaker
declares interface type variable.s = Dog{}
ands = Cat{}
assign different types.fmt.Println(s.Speak())
calls Speak method.
Output
Woof!
Meow!
Conclusion
Go datatypes provide a robust and flexible system for working with data. Understanding these types, from basic to complex, is crucial for effective Go programming. Each type serves a specific purpose. Using different types helps you write efficient code.