[Getting Started with Golang] Introduction and Basic Grammar Learning

The following is a blog about getting started with Golang, record it. (If you have a language foundation, you can basically get started in 1 hour)

1. What is Golang?

Golang (also known as Go) is a programming language developed by Google Inc. It is a statically typed, compiled, concurrent language designed for building efficient, scalable, and maintainable software systems. Golang has simple syntax, fast compilation speed and good performance, so it is loved and adopted by more and more developers.

2. Install Golang

Before starting to use Golang, we need to install the Golang development environment first. Golang supports multiple operating system platforms such as Windows, Mac OS X, and Linux, and you can choose the corresponding version to install according to your needs. Here are the installation steps:

  1. Open  the Golang official website  and download the installation package for the corresponding system.
  2. Double-click the installation package to install it, and follow the prompts to complete the installation process step by step.

After the installation is complete, we can enter on the command line go versionto check whether the installation is successful.

3. Write the Hello World program

After installing Golang, we can try to write the simplest program - Hello World.

  1. Create a  hello.go file named , and open it with a text editor.
  2. Enter the following code:
package main import "fmt" func main() { fmt.Println("Hello, World!") }
  1. Save the file, and enter the directory where the file is located on the command line.
  2. Run the program and enter the command  go run hello.go.

If everything worked, you should see the output: Hello, World!. Congratulations on successfully writing your first Golang program!

4. Basic Grammar

Next let's learn some basic syntax of Golang:

4.1 Variables

Variables are very important concepts in programs, they are used to store data. In Golang, we can declare variables using varthe keyword . For example:

var name string = "Alice"

The above code declares a variable of type String namecalled and initializes it to "Alice". We can also omit the type and let the compiler infer the variable type automatically:

var name = "Alice"

Alternatively, we can use :=the operator to simplify variable declaration and initialization:

name := "Alice"

This is equivalent to declaring and initializing a string type variable namenamed .

4.2 Arrays and slices

An array is a fixed-size, homogeneous data structure. In Golang, we can define an integer array of length 5 using:

var arr [5]int

Note that the length of the array needs to be specified when it is created and cannot be changed. We can access array elements using subscripts:

arr[0] = 1 // 将第一个元素设置为1
fmt.Println(arr[0]) // 输出:1

In addition to arrays, Golang also provides slices, a dynamically sized data structure. Unlike arrays, slices can grow or shrink in length as needed. Here is an example of creating and initializing a slice:

var s []int = make([]int, 5) // 创建一个长度为5的整型切片
s[0] = 1 // 将第一个元素设置为1
fmt.Println(s[0]) // 输出:1

4.3 Control flow

When writing programs, we usually need to perform different operations based on different conditions. In Golang, we can use statements such as if, for, and switch to control the program flow.

The if statement is used to perform different actions based on a condition. Here is an example of a simple if:

if age >= 18 {
    fmt.Println("成年人")
} else {
    fmt.Println("未成年人")
}

If ageis greater than or equal to 18, then output "成年人"; otherwise output "未成年人".

The for loop is used to repeatedly execute a specified block of code and can take many forms. The following are the most common forms of for loops:

for i := 0; i < 5; i++ {
    fmt.Println(i)
}

The above code will output numbers from 0 to 4.

The switch statement is used to perform different actions according to different situations. Here is an example:

switch dayOfWeek {
case "Monday":
    fmt.Println("星期一")
case "Tuesday":
    fmt.Println("星期二")
case "Wednesday":
    fmt.Println("星期三")
default:
    fmt.Println("其他")
}

If the value dayOfWeekof is "Monday", then output "星期一"; if it is "Tuesday", then output "星期二", and so on. If the value does not match any of the cases, the statements in the default code block are executed.

5. Concurrent programming

Golang is a concurrent language that provides a wealth of concurrent programming tools, allowing us to easily write efficient concurrent programs.

There are many ways to implement concurrent programming in Golang, the most common of which is to use goroutines and channels. Goroutine is a lightweight thread managed by Golang runtime, which can execute multiple tasks in one program at the same time; channel is used to transfer data between goroutines.

Here is an example of concurrent computation using goroutines and channels:

func square(num int, out chan<- int) {
    out <- num * num
}

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    results := make(chan int)

    for _, num := range numbers {
        go square(num, results)
    }

    for i := 0; i < len(numbers); i++ {
        fmt.Println(<-results)
    }
}

This code will square each number in numbersthe list and output the result. A goroutine started with gothe keyword will execute squarethe function asynchronously. The second parameter of the function outis a write-only channel, which is used to send the calculation result to the main thread; the main thread <-resultsreceives the calculation result through and outputs it.

The above are some basic Golang syntax and concurrent programming methods. If you want to learn Golang in depth, you can refer to official documents or other related books.

Guess you like

Origin blog.csdn.net/gongzi_9/article/details/130113307