1. Basic Syntax
Hello World:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Variables:
var x int = 10
y := 20// short variable declaration
Constants:
const pi = 3.14
2. Data Types
Basic Types:
int, float64, string, bool
Composite Types:
Arrays:
var arr [5]int
arr[0] = 1
Slices:
slice := []int{1, 2, 3}
Maps:
m := make(map[string]int)
m["key"] = 1
Control Structures
If Statement:
if x > 0 {
fmt.Println("Positive")
}
Switch Statement:
switch x {
case 1:
fmt.Println("One")
default:
fmt.Println("Not One")
}
Loops:
for i := 0; i < 5; i++ {
fmt.Println(i)
}for _, value := range slice {
fmt.Println(value)
}
Functions
Defining Functions:
func add(a int, b int) int {
return a + b
}
Multiple Return Values:
func divide(a, b int) (int, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
Structs and Interfaces
Structs:
type Person struct {
Name string
Age int
}p := Person{Name: "Alice", Age: 30}
Interfaces:
type Animal interface {
Speak() string
}type Dog struct{}func (d Dog) Speak() string {
return "Woof!"
}
Error Handling
Basic Error Handling:
result, err := divide(4, 0)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
Concurrency
Goroutines:
go func() {
fmt.Println("Running in a goroutine")
}()
Channels:
ch := make(chan int)
go func() {
ch <- 42
}()
value := <-ch
fmt.Println(value)
Packages
Importing Packages:
import (
"fmt"
"math"
)
Creating Your Own Package:
-
- Create a directory with your package name.
- Create a
.go
file with the same package name. - Use
import "your-package-name"
to include it.
Testing
Basic Test Structure:
package yourpackage
import "testing"
func TestAdd(t *testing.T) {
got := add(1, 2)
want := 3
if got != want {
t.Errorf("got %d, want %d", got, want)
}
}
Running Tests:
Common Commands
Create a New Module:
go mod init module-name
Build the Project:
Run the Project:
go run main.go
Get Package:
go get package-name
Useful Resources
- Official Documentation: golang.org/doc
- Effective Go: Effective Go
- Go by Example: Go by Example