Local variables are defined inside a function and are accessible only within that function. They help in encapsulating data and preventing unintended modifications by other parts of the code.
- Declared using
var
or:=
(short declaration syntax).
package main
import "fmt"
func main() {
var message string = "Hello, Go!" // Using var
count := 10 // Using := (short declaration)
fmt.Println(message, count)
}
Package-level variables are accessible only within the package. They help in sharing data between multiple functions in the same package.
- Declared at the beginning, after the
import
statement.
package main
import "fmt"
var packageVar = "Accessible within the package"
func main() {
fmt.Println(packageVar)
}
Global variables and functions are accessible across the entire application. They are useful for storing configurations and reusable utility functions.
- Must be exported by capitalizing their names.
package main
import "fmt"
var GlobalVar = "I am global"
func GlobalFunction() {
fmt.Println("I am a global function")
}
Modules allow code reuse and separation of concerns. You can import functions from other modules as follows:
import "myapp/utility"
- The function needs to be exported by capitalizing its name in the module where it is defined.
Go provides a rich set of data types to handle various types of data efficiently.
int
,int8
,int16
,int32
,int64
uint
,uint8
,uint16
,uint32
,uint64
uintptr
for storing pointer addresses
var a int = 10
var b int8 = 127
Floating-point numbers are used for fractional calculations.
float32
,float64
var pi float64 = 3.1415
Booleans are used for conditional statements and logical operations.
var isAvailable bool = true
Strings store text data and are immutable.
var message string = "Hello, Go!"
Go supports complex numbers with real and imaginary parts.
complex64
,complex128
var c complex64 = complex(2, 3)
Arrays and slices store collections of elements.
var arr [3]int = [3]int{1, 2, 3} // Fixed size array
slice := []int{1, 2, 3, 4, 5} // Dynamic size
Maps are used for fast lookup operations.
var myMap map[string]int = map[string]int{"a": 1, "b": 2}
Useful for performance optimization, cryptography, and low-level programming.
and := 5 & 3 // AND operation
or := 5 | 3 // OR operation
xor := 5 ^ 3 // XOR operation
leftShift := 5 << 1 // Left shift
rightShift := 5 >> 1 // Right shift
Used to iterate over slices, maps, and arrays.
nums := []int{1, 2, 3, 4}
for index, value := range nums {
fmt.Println(index, value)
}
Useful for short, one-time-use functions.
func() {
fmt.Println("Hello from an anonymous function!")
}()
Accept a variable number of arguments.
func sum(nums ...int) int {
total := 0
for _, num := range nums {
total += num
}
return total
}
Go uses composition instead of classical inheritance.
type Animal struct {
Name string
}
type Dog struct {
Animal
Breed string
}
Lightweight thread for parallel execution.
go func() {
fmt.Println("Running in a goroutine")
}()
Used for communication between goroutines.
messages := make(chan string)
go func() { messages <- "Hello, Channel!" }()
fmt.Println(<-messages)
Efficient way to handle large files without consuming too much memory.
import (
"bufio"
"os"
)
file, _ := os.Open("largefile.txt")
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
Used for handling unexpected errors gracefully.
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
panic("Something went wrong!")
Used for data serialization and API communication.
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
data := `{"name":"John", "age":30}`
var person Person
json.Unmarshal([]byte(data), &person)
fmt.Println(person.Name, person.Age)
Go uses interfaces for polymorphism.
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!" }
Use go mod
for package management.
go mod init myapp
go get github.com/gin-gonic/gin
Write tests with the testing
package.
import "testing"
func TestSum(t *testing.T) {
result := sum(1, 2, 3)
if result != 6 {
t.Errorf("Expected 6 but got %d", result)
}
}