Day 6: Exploring Data Types in Go - Numbers, Strings, and Booleans
Go is a statically typed language, which means variables must be declared with a specific type. Today, we’ll explore Go’s core data types, including numbers, strings, and booleans, and how to work with them.
Step 1: Integer Types
Go has various integer types, both signed and unsigned:
int
- typically 32 or 64 bits, depending on the architectureint8
,int16
,int32
,int64
- explicitly sized signed integersuint8
,uint16
,uint32
,uint64
- unsigned integers
Example:
var a int = 10
var b uint64 = 10800000000
Step 2: Floating Point Types
Go supports floating-point numbers with float32
and float64
:
var x float32 = 3.14
var y float64 = 1.6180339887
By default, floating-point numbers are assumed to be of type float64
.
Step 3: Strings
Strings in Go are immutable sequences of bytes, meaning once created, they cannot be modified. You can concatenate strings using the +
operator:
name := "John"
greeting := "Hello, " + name
fmt.Println(greeting) // Output: Hello, John
To get the length of a string, use the len()
function:
fmt.Println(len(name)) // Output: 4
Step 4: Boolean Type
The boolean type in Go is bool
, with two possible values: true
or false
:
var isGoAwesome bool = true
Practical Exercise
Write a program that defines variables for a person’s age, height (in meters), and name. Print a message including these details using string concatenation and formatted printing:
package main
import "fmt"
func main() {
var age int = 30
var height float64 = 1.75
var name string = "Alice"
fmt.Printf("%s is %d years old and is %.2f meters tall.\n", name, age, height)
}