Go Basics: Data Types, Control Flow, and More!
In this section, we'll cover important Go concepts such as data types, control flow structures, functions, and concurrency. These concepts are essential to mastering Go programming.
Step 5: Data Types in Go
Go is a statically typed language, which means every variable has a specific type that is defined at compile time. Here's an overview of Go's basic data types:
- Boolean:
bool
– Represents true or false values. - Integer types:
int
,int8
,int16
,int32
,int64
– Whole numbers. - Unsigned integer types:
uint
,uint8
,uint16
,uint32
,uint64
– Whole numbers without a sign (positive values only). - Floating point types:
float32
,float64
– Numbers with decimal points. - Complex types:
complex64
,complex128
– Complex numbers (real and imaginary parts). - String:
string
– A sequence of characters. - Byte: Alias for
uint8
, often used to represent a byte of data.
package main
import "fmt"
func main() { var age int = 30 var isActive bool = true var salary float64 = 55000.75 var name string = "Abhi K"
fmt.Println("Age:", age) fmt.Println("Active Status:", isActive) fmt.Println("Salary:", salary) fmt.Println("Name:", name)
}
Step 6: Arrays and Slices
Arrays
Arrays have a fixed size, meaning once the size is defined, it cannot be changed. Arrays store elements of the same type.
package main
import "fmt"
func main() { var numbers [5]int numbers[0] = 10 numbers[1] = 20
fmt.Println("Array:", numbers)
}
Slices
Slices are more flexible than arrays and can grow or shrink dynamically. They are a more commonly used structure in Go.
package main
import "fmt"
func main() { numbers := []int{1, 2, 3, 4, 5} numbers = append(numbers, 6)
fmt.Println("Slice:", numbers)
}
Step 7: Control Structures
Go has several control flow structures that help with decision-making and looping.
If-Else Statement
package main
import "fmt"
func main() { age := 18 if age >= 18 { fmt.Println("You are an adult!") } else { fmt.Println("You are a minor!") } }
Switch Statement
package main
import "fmt"
func main() { day := "Monday"
switch day { case "Monday": fmt.Println("Start of the workweek!") case "Friday": fmt.Println("Almost weekend!") default: fmt.Println("Regular day") }
}
For Loop
Go only has one loop construct, the for
loop. It can be used in a variety of ways.
package main
import "fmt"
func main() { for i := 1; i <= 5; i++ { fmt.Println(i) } }
Step 8: Functions
Functions allow you to group code into reusable blocks. Here's how you define and use functions in Go.
Function with a Return Type
package main
import "fmt"
// Function that returns a string func greet(name string) string { return "Hello, " + name + "!" }
func main() { message := greet("John") fmt.Println(message) }
Function that Returns Multiple Values
package main
import "fmt"
// Function that returns two values func add(a, b int) (int, int) { return a + b, a * b }
func main() { sum, product := add(5, 3) fmt.Printf("Sum: %d, Product: %d\n", sum, product) }
Step 9: Structs
Structs allow you to define custom data types that can hold multiple pieces of data, often related. Here's an Code of defining and using structs in Go.
package main
import "fmt"
// Define a struct type Person struct { Name string Age int }
func main() { // Create an instance of the Person struct p := Person{"John", 30}
fmt.Println("Name:", p.Name) fmt.Println("Age:", p.Age)
}
Step 10: Interfaces
Go uses interfaces to define a set of behaviors. Types can implement interfaces by defining the methods declared in the interface.
package main
import "fmt"
// Define an interface type Speaker interface { Speak() string }
// Implement the interface for a struct type Person struct { Name string }
func (p Person) Speak() string { return "Hello, my name is " + p.Name }
func main() { p := Person{"John"} var speaker Speaker = p
fmt.Println(speaker.Speak())
}
Step 11: Error Handling
In Go, error handling is explicit, unlike other languages that use exceptions. Here's how you handle errors in Go.
package main
import ( "fmt" "errors" )
func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil }
func main() { result, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Result:", result) } }
Step 12: Concurrency in Go
Go's built-in concurrency model allows for efficient handling of multiple tasks simultaneously.
Goroutines
A goroutine is a lightweight thread managed by the Go runtime. You can start a goroutine by adding go
before a function call.
package main
import "fmt"
func printHello() { fmt.Println("Hello from Goroutine!") }
func main() { go printHello() // Start the goroutine
// Give time for the goroutine to execute fmt.Scanln() // Wait for user input
}
Channels
Channels are used to communicate between goroutines. They allow safe data exchange.
package main
import "fmt"
func greet(ch chan string) { ch <- "Hello from Goroutine!" // Send data to channel }
func main() { ch := make(chan string) // Create a channel
go greet(ch) // Start goroutine message := <-ch // Receive data from the channel fmt.Println(message)
}
Next Steps
- Feel free to check out more resources on Go’s Official Documentation.
- Explore Go’s concurrency features in more depth, including select statements and buffered channels.
- Dive deeper into Go's standard library to see the wealth of utilities and packages it offers.
- Practice building small projects to solidify your understanding of these concepts.
With these foundational concepts, you're well on your way to becoming proficient in Go!
Stay connected and keep learning!
Connect with Me
Feel free to reach out for collaborations, questions, or guidance related to Golang, JavaScript, and System Design.
- GitHub: abhishekkushwahaa
- LinkedIn: Abhishek Kushwaha
Let’s connect and build amazing projects together!