Overview of Data Types in Go

In this lesson, we'll explore the different types of data Go can handle and how to work with them.
Types in Go
In Go, variables can hold different kinds of data, known as data types. Since Go is a statically typed language, the compiler needs to know the type of every variable either explicitly or through inference. A type defines both the possible values a variable can hold and the operations you can perform on that data.
Here’s a quick breakdown of the main types in Go:
Elementary (Primitive) Types: Basic types such as
int,float,bool, andstring.Structured (Composite) Types: More complex types like
struct,array,slice,map, andchannel.Interfaces: These describe the behaviour of a type by defining a set of methods.
For structured types that haven’t been assigned a value yet, they default to nil.
Declaring Variables
To declare a variable in Go, you use the var keyword followed by the variable name and its type:
var var1 type1
Here, var1 is the variable, and type1 is its type.
Function Types
Functions also have types, specifically a return type. The type of the function’s return value is declared after the function’s parameters:
func FunctionName(a typeA, b typeB) typeFunc
In this example, typeFunc is the return type of the function. If the function returns multiple values, their types are listed in parentheses:
func FunctionName(a typeA, b typeB) (t1 type1, t2 type2)
The return statement would then look like this:
return var1, var2
User-Defined Data Types
Go allows you to define custom data types. For example, you can create an alias for a type:
type IZ int
Now, instead of declaring an int, you can use IZ:
var a IZ = 5
You can also declare multiple type aliases in a factored format:
type (
IZ int
FZ float32
STR string
)
In this example, IZ, FZ, and STR are aliases for int, float32, and string respectively.
Type Conversion
Sometimes, you’ll need to convert a value from one type to another. Go does not perform implicit type conversions, so all conversions must be done explicitly. Here's an example of type-casting:
valueOfTypeB = typeB(valueOfTypeA)
If you have a floating-point variable and want to convert it to an integer, you would do this:
number := 5.2
intValue := int(number)
After converting, the value of number changes from 5.2 to 5 as the decimal is truncated.
Now that we've covered the basics of data types in Go, it's time to move on to storing data in the next lesson.




