Go Syntax Basics
Introduction to Go Syntax
Go (Golang) is a statically typed, compiled programming language designed for simplicity and efficiency. Understanding its basic syntax is crucial for writing clean and effective code.
Basic Syntax Elements
Package Declaration
Every Go program starts with a package declaration. The main
package is special and defines an executable program.
package main
Import Statements
Importing necessary packages is done using the import
keyword:
import (
"fmt"
"math"
)
Variable Declarations
Go supports multiple ways of declaring variables:
// Explicit type declaration
var name string = "LabEx"
// Type inference
age := 25
// Multiple variable declaration
var (
x, y int
firstName string
)
Data Types
Go provides several fundamental data types:
Type |
Description |
Example |
int |
Integer |
var count int = 10 |
float64 |
Floating-point number |
var price float64 = 19.99 |
string |
Text |
name := "LabEx" |
bool |
Boolean |
isActive := true |
Control Structures
Conditional Statements
if condition {
// code block
} else {
// alternative block
}
Loops
Go primarily uses the for
loop:
// Traditional loop
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// While-like loop
for condition {
// code block
}
Functions
Functions are defined using the func
keyword:
func add(a, b int) int {
return a + b
}
// Multiple return values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
Error Handling
Go uses explicit error handling:
result, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
Syntax Flow Visualization
graph TD
A[Start] --> B{Package Declaration}
B --> C[Import Statements]
C --> D[Variable Declarations]
D --> E[Function Definitions]
E --> F[Control Structures]
F --> G[Error Handling]
G --> H[End]
Best Practices
- Use clear and descriptive variable names
- Keep functions small and focused
- Handle errors explicitly
- Follow Go formatting guidelines
By mastering these basic syntax elements, you'll be well-prepared to write efficient Go programs with LabEx's programming resources.