goLang tutorials from basic to advance with examples

 Here’s a structured guide for learning Go (Golang) from basic to advanced levels with examples for each stage. Go is a statically typed, compiled language that is known for simplicity, performance, and concurrency support, making it a great choice for building web applications, microservices, and more.

Part 1: Go Basics

1. Go Installation

  • Install Go: Download and install Go from the official site.
  • Setup your workspace: Typically, Go code is written in the GOPATH directory, but in modern Go development, the module system (go mod) is used.
    mkdir -p ~/go/src

2. Hello World in Go

Create a simple "Hello, World!" program:

package main import "fmt" func main() { fmt.Println("Hello, World!") }

Run the program:

go run hello.go

3. Variables and Data Types

Go is statically typed, meaning variables must be declared with a type.

package main import "fmt" func main() { var age int = 25 name := "Alice" // Short declaration fmt.Println("Name:", name) fmt.Println("Age:", age) }

Go supports the following data types:

  • Integers: int, int32, int64
  • Floating-point numbers: float32, float64
  • Booleans: bool
  • Strings: string

4. Control Flow: If, Else, Switch

  • If statement:

    package main import "fmt" func main() { num := 10 if num > 5 { fmt.Println("Greater than 5") } else { fmt.Println("Less than or equal to 5") } }
  • Switch statement:

    package main import "fmt" func main() { day := 3 switch day { case 1: fmt.Println("Monday") case 2: fmt.Println("Tuesday") case 3: fmt.Println("Wednesday") default: fmt.Println("Other day") } }

Part 2: Intermediate Go

1. Arrays and Slices

  • Arrays are fixed in size:

    var arr [5]int arr[0] = 1 fmt.Println(arr)
  • Slices are dynamic and more commonly used:

    package main import "fmt" func main() { slice := []int{1, 2, 3} slice = append(slice, 4) fmt.Println(slice) }

2. Functions

Functions in Go are defined with the func keyword.

package main import "fmt" // Function with parameters and return value func add(a int, b int) int { return a + b } func main() { sum := add(2, 3) fmt.Println("Sum:", sum) }
  • Multiple Return Values:
    package main import "fmt" func swap(a, b int) (int, int) { return b, a } func main() { x, y := swap(1, 2) fmt.Println(x, y) }

3. Structs

Structs allow you to group related data.

package main import "fmt" type Person struct { FirstName string LastName string Age int } func main() { p := Person{FirstName: "John", LastName: "Doe", Age: 30} fmt.Println(p) }

4. Methods

Go allows you to define methods on types.

package main import "fmt" type Rectangle struct { Width, Height int } // Method on Rectangle func (r Rectangle) Area() int { return r.Width * r.Height } func main() { rect := Rectangle{Width: 5, Height: 10} fmt.Println("Area of Rectangle:", rect.Area()) }

Part 3: Advanced Go

1. Concurrency in Go (Goroutines and Channels)

Go's concurrency model is one of its key features. It uses goroutines (lightweight threads) and channels for communication between them.

  • Goroutines: Concurrent functions run as goroutines.

    package main import ( "fmt" "time" ) func sayHello() { fmt.Println("Hello from Goroutine!") } func main() { go sayHello() // Starts a new Goroutine time.Sleep(1 * time.Second) // Give time for the goroutine to run }
  • Channels: Used to communicate between goroutines.

    package main import ( "fmt" "time" ) func count(ch chan int) { for i := 1; i <= 5; i++ { ch <- i } close(ch) } func main() { ch := make(chan int) go count(ch) for num := range ch { fmt.Println(num) } }

2. Error Handling

Go handles errors explicitly using the error type.

package main import ( "errors" "fmt" ) func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("cannot divide by zero") } return a / b, nil } func main() { result, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Result:", result) } }

3. Interfaces

Go uses interfaces to define behavior without needing inheritance.

package main import "fmt" type Shape interface { Area() float64 } type Rectangle struct { Width, Height float64 } func (r Rectangle) Area() float64 { return r.Width * r.Height } type Circle struct { Radius float64 } func (c Circle) Area() float64 { return 3.14 * c.Radius * c.Radius } func main() { var shape Shape shape = Rectangle{Width: 5, Height: 10} fmt.Println("Rectangle Area:", shape.Area()) shape = Circle{Radius: 7} fmt.Println("Circle Area:", shape.Area()) }

4. Package and Modular Programming

  • Creating packages: Go allows you to create your own packages to organize code.

Example: Create a file mathutil.go inside a mathutil directory:

// mathutil.go package mathutil func Add(a, b int) int { return a + b }

Use it in your main.go:

package main import ( "fmt" "your_module_path/mathutil" // Update with the actual module path ) func main() { result := mathutil.Add(5, 3) fmt.Println("Result:", result) }

5. Web Development (Gin Web Framework Example)

One of the popular Go web frameworks is Gin. To get started with a simple web app, follow this example:

  • Install Gin:

    go get -u github.com/gin-gonic/gin
  • Basic Gin Web Server:

    package main import "github.com/gin-gonic/gin" func main() { router := gin.Default() router.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "Hello, World!", }) }) router.Run(":8080") }

Run the app:

go run main.go

This will start a web server on http://localhost:8080.


Part 4: Advanced Go Topics

1. Go Modules and Dependency Management

Go modules allow you to manage project dependencies.

  • Initialize a Go module:

    go mod init your_module_name
  • Add dependencies:

    go get github.com/gin-gonic/gin
  • To see the dependencies, you can use:


    go list -m all

2. Testing

Go comes with built-in testing support.

  • Create a file main_test.go for writing tests:
    package main import "testing" func TestAdd(t *testing.T) { result := Add(2, 3) if result != 5 { t.Errorf("Add(2, 3) = %d; expected 5", result) } }

Run tests:

go test

3. Profiling and Optimization

Go provides profiling tools to help optimize your code. You can use pprof for CPU and memory profiling to detect bottlenecks.


Conclusion

This tutorial takes you from basic Go syntax to advanced topics such as concurrency, testing, web development, and more. Go’s simplicity and performance make it an excellent choice for many types of applications, and by practicing these concepts, you’ll be able to build robust systems. Continue exploring more advanced features as you grow in your Go development journey!

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics