ClickCease

Go Programming

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:

2. Data Types

Basic Types:

int, float64, string, bool

Composite Types:

  Arrays:

  Slices:

  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:

Creating Your Own Package:

    1. Create a directory with your package name.
    2. Create a .go file with the same package name.
    3. 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:

Build the Project:

Run the Project:

Get Package:

Useful Resources

 

Facebook
X
LinkedIn
Pinterest
WhatsApp