Sure! Go (also known as Golang) is a statically typed, compiled programming language designed for simplicity, efficiency, and readability. Here's a breakdown of the basic syntax in Go:
1. Hello World Example
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Explanation:
package main: Defines the package name. The main package is special — it tells the Go compiler that the program should compile as an executable.
import "fmt": Imports the fmt package, which contains functions for formatted I/O (like Println).
func main(): The entry point of a Go program. Execution starts here.
fmt.Println(...): Prints a line to the console.
2. Variables
Declaration:
var x int = 10
Type Inference:
var y = 20
Short Declaration (inside functions only):
z := 30
3. Data Types
Common types:
int, int8, int16, int32, int64
uint, uint8, uint16, uint32, uint64
float32, float64
string
bool
4. Functions
func add(a int, b int) int {
return a + b
}
- Functions start with
func
- Parameters are typed
- Return type comes after the parameter list
5. Control Structures
If Statement:
if x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is 10 or less")
}
For Loop:
for i := 0; i < 5; i++ {
fmt.Println(i)
}
While-style Loop:
i := 0
for i < 5 {
fmt.Println(i)
i++
}
Infinite Loop:
for {
// loop forever
}
6. Arrays and Slices
Array:
var arr [3]int = [3]int{1, 2, 3}
Slice:
s := []int{1, 2, 3}
s = append(s, 4)
7. Maps (Dictionaries)
m := make(map[string]int)
m["a"] = 1
fmt.Println(m["a"])
8. Structs
type Person struct {
Name string
Age int
}
p := Person{Name: "Alice", Age: 30}
fmt.Println(p.Name)
9. Pointers
x := 10
p := &x
fmt.Println(*p) // prints 10
10. Interfaces
type Speaker interface {
Speak() string
}
type Dog struct{}
func (d Dog) Speak() string {
return "Woof!"
}
11. Error Handling
import "errors"
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
Summary
Go emphasizes:
- Simplicity and clarity
- Static typing and safety
- Fast compilation
- Built-in concurrency (via goroutines and channels)
Let me know if you'd like to dive deeper into any specific part!