codes

gitee

How to Run a Go Program

As an example, let’s print “Hello World”:

1
2
3
4
5
6
7
8
// main.go
package main // A file with package main can be run directly

import "fmt"

func main() {
fmt.Println("Hello, World!")
}
1
2
3
4
5
# Run directly
go run main.go
# Or compile and then run
go build main.go
./main.exe

Variable Declaration and Data Types

A variable is an identifier that points to an address in memory, typically used for storing data. A data type represents
the type of a variable, which determines how much space it occupies in memory. Assignment means placing a value into the
memory address pointed to by the variable. Later, you can use this variable to retrieve the data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import "fmt"

func main() {
// Declare and initialize an integer variable
var age int = 25
fmt.Println("Age:", age)

// Declare and initialize a floating-point variable
var height float64 = 1.75
fmt.Println("Height:", height)

// Declare and initialize a string variable
var name string
name = "Alice"
fmt.Println("Name:", name)

// Declare and initialize a boolean variable
isStudent := true // Automatic type inference, most commonly used way to declare variables
fmt.Println("Is student:", isStudent)
}

Control Flow

Control flow defines the execution order of our program.

Sequential Execution

Sequential execution runs from top to bottom, which is the normal execution process of our program.

1
2
3
4
5
6
7
8
9
package main

import "fmt"

func main() {
fmt.Println("Step 1")
fmt.Println("Step 2")
fmt.Println("Step 3")
}

Selection

选择就是根据满足不同的条件来执行不同的代码
选择的流程分为单分支和多分支

Single Branch

A single branch refers to having only one branch node and a single conditional check.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import "fmt"

func main() {
var score int = 85

if score >= 60 {
fmt.Println("Pass")
} else {
fmt.Println("Fail")
}
}

Multiple Branches

Multiple branches involve several branch nodes and multiple condition checks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

import "fmt"

func main() {
var score int = 85

if score >= 90 {
fmt.Println("A")
} else if score >= 80 {
fmt.Println("B")
} else if score >= 70 {
fmt.Println("C")
} else {
fmt.Println("D")
}
}

Loops

Loops represent a process of repeated execution.

1
2
3
4
5
6
7
8
9
10
11
package main

import "fmt"

func main() {
// Define a temporary variable i, initialize it to 1; loop condition is i <= 5
for i := 1; i <= 5; i++ {
fmt.Println(i)
}
}

Functions

A function is essentially a closure with its own scope. We can define a block of code as a function, which can accept
zero or more inputs, execute the logic within the function body, and return zero or more outputs upon completion. Using
functions helps extract common logic and simplifies our code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import "fmt"

// Define a function that takes two integer parameters and returns their sum
func add(a int, b int) int {
return a + b
}

func main() {
result := add(5, 3)
fmt.Println("Result:", result) // Output: Result: 8
}

Classes / Structs

Classes / Structs

A class is an abstract structure that contains data and methods (functions). We can define it, and to use it, we need to
instantiate it—essentially allocating space in memory to store it. The size of a class depends on what kind of data it
defines internally (e.g., int), and the compiler automatically determines how much space to allocate. A class can have
multiple instantiated objects—that is, multiple different variables—but these variables all conform to the same
structural definition.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import "fmt"

// Define a struct Person with Name and Age fields
type Person struct {
Name string
Age int
}

// Add a method SayHello to Person
func (p Person) SayHello() {
fmt.Printf("Hello, my name is %s and I am %d years old.\n", p.Name, p.Age)
}

func main() {
// Create an instance of Person
person := Person{Name: "Alice", Age: 25}

// Call the method
person.SayHello()
// Output: Hello, my name is Alice and I am 25 years old.
}

Interfaces

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main

import "fmt"

// Define an interface Animal with a Speak method
type Animal interface {
Speak() string // Any type implementing the Speak() method can be considered an Animal
}

// Define a struct Dog
type Dog struct {
Name string
}

// Implement the Speak method for Dog
func (d Dog) Speak() string {
return "Woof! My name is " + d.Name
}

// Define a struct Cat
type Cat struct {
Name string
}

// Implement the Speak method for Cat
func (c Cat) Speak() string {
return "Meow! My name is " + c.Name
}

func main() {
// Declare an Animal interface variable
var a Animal

// Create a Dog instance
dog := Dog{Name: "Buddy"}
a = dog // Dog implements the Animal interface, so it can be assigned to a
fmt.Println(a.Speak()) // Output: Woof! My name is Buddy

// Create a Cat instance
cat := Cat{Name: "Whiskers"}
a = cat // Cat also implements the Animal interface
fmt.Println(a.Speak()) // Output: Meow! My name is Whiskers

// Different types can be processed uniformly
animals := []Animal{dog, cat}
for _, animal := range animals {
fmt.Println(animal.Speak())
}
}

Frameworks

To simplify development, programmers extract common logic into functions, or encapsulate them into classes and methods.
As this process continues and evolves, frameworks are born. In my understanding, a library is a collection of commonly
used functions and classes, allowing users to incorporate various libraries as they prefer. On the other hand, a
framework tends to define a set of project conventions and templates, where users develop based on the framework’s
predefined standards and structures. However, the distinction between the two terms is often blurred, and they are
frequently used interchangeably.

web

The programs we’ve written so far run locally. To allow users around the world to access them, we need to expose them
over the network. Web frameworks wrap the language’s native networking libraries and provide methods for building web
services. A commonly used web framework in Go is Gin.

1
go get "github.com/gin-gonic/gin"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
"github.com/gin-gonic/gin"
)

func main() {
// Create a default router engine
r := gin.Default()

// Define a GET endpoint
r.GET("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello from Gin!",
})
})

// Start HTTP server on port 8080 by default
r.Run(":8080")
}

Visit localhost:8080/hello to see the output.

db

So far, we’ve been using variables to store data, but variable data resides in memory and will be lost once the program
stops. When restarting the program, the operating system may allocate a different memory space. Therefore, we need
persistent storage for our data, which leads us to database systems. A commonly used database framework in Go is GORM.

1
go get "gorm.io/driver/sqlite" "gorm.io/gorm" "github.com/glebarez/sqlite"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main

import (
"github.com/glebarez/sqlite"
// Requires: go env -w CGO_ENABLED=1
// Also requires GCC, but this is the official implementation, which is better
// "gorm.io/driver/sqlite"
"gorm.io/gorm"
)

// Define a struct User corresponding to a database table
type User struct {
gorm.Model
Name string
Email string `gorm:"unique"`
}

func main() {
// Connect to SQLite database (filename: test.db)
db, err := gorm.Open(sqlite.Open("./dev.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}

// Automatically migrate schema
db.AutoMigrate(&User{})

// Create a record
db.Create(&User{Name: "Alice", Email: "alice@example.com"})

// Query a record
var user User
db.Where("name = ?", "Alice").First(&user)
println("Found user:", user.Name)

// Update a record
db.Model(&user).Update("Name", "Bob")

// Delete a record
db.Delete(&user)
}

Extensions

○ Multithreading / Microservices / Reflection - Dynamic Proxy / File Operations / Network Programming /
○ Framework Principles / Manual Implementation
○ WASM / gRPC


本站总访问量