Go Programming Language Tutorial
Go Programming Language Tutorial
Go (or Golang) is a statically typed, compiled programming language designed by Google. It’s known
for simplicity, speed, and a robust concurrency model.
1. Installation
1. Download and install Go from golang.org.
2. Verify installation:
bash
Copy code
go version
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Run it:
bash
Copy code
go run hello.go
To build a binary:
bash
Copy code
go build hello.go
./hello
3. Go Language Basics
Variables
go
Copy code
package main
import "fmt"
func main() {
// Declare and initialize variables
var a int = 10
b := 20 // Short declaration
fmt.Println("a:", a, "b:", b)
}
Data Types
• Basic types: int, float64, string, bool
• Complex types: struct, array, slice, map, interface
Constants
go
Copy code
const Pi = 3.14
const (
A = 1
B = "Go"
)
4. Functions
go
Copy code
package main
import "fmt"
func main() {
result := add(3, 5)
fmt.Println("Sum:", result)
}
Multiple Return Values
go
Copy code
func divide(a, b int) (int, int) {
return a / b, a % b
}
5. Control Flow
If/Else
go
Copy code
if x > 10 {
fmt.Println("Greater")
} else {
fmt.Println("Smaller or Equal")
}
For Loops
go
Copy code
for i := 0; i < 10; i++ {
fmt.Println(i)
}
Switch
go
Copy code
switch day {
case "Monday":
fmt.Println("Start of the week")
case "Friday":
fmt.Println("Weekend!")
default:
fmt.Println("Midweek")
}
6. Arrays, Slices, and Maps
Arrays
go
Copy code
var arr [5]int
arr[0] = 1
fmt.Println(arr)
Slices
go
Copy code
slice := []int{1, 2, 3}
slice = append(slice, 4)
fmt.Println(slice)
Maps
go
Copy code
m := map[string]int{"a": 1, "b": 2}
fmt.Println(m["a"])
func main() {
p := Person{Name: "John", Age: 30}
fmt.Println(p)
}
Methods
go
Copy code
func (p Person) Greet() {
fmt.Println("Hello, my name is", p.Name)
}
8. Goroutines and Channels
Goroutines
go
Copy code
go func() {
fmt.Println("Goroutine")
}()
Channels
go
Copy code
ch := make(chan int)
// Sender
go func() { ch <- 42 }()
// Receiver
val := <-ch
fmt.Println(val)
9. Error Handling
go
Copy code
package main
import (
"errors"
"fmt"
)
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}
10. Modules and Packages
Create a Module
bash
Copy code
go mod init example.com/myapp
Import Packages
Create a directory structure:
go
Copy code
myapp/
├── main.go
├── greet/
│ └── greet.go
greet.go:
go
Copy code
package greet
import "fmt"
func Hello() {
fmt.Println("Hello from package!")
}
main.go:
go
Copy code
package main
import "example.com/myapp/greet"
func main() {
greet.Hello()
}
11. Testing
Go has a built-in testing framework:
go
Copy code
package main
import "testing"
func TestAdd(t *testing.T) {
result := add(2, 3)
if result != 5 {
t.Errorf("Expected 5, got %d", result)
}
}
Run tests:
bash
Copy code
go test
This covers the core concepts of Go programming. You can expand by exploring advanced topics like
reflection, interfaces, and build optimizations.