Getting Started with Go Language Basics: From Syntax to Core Concepts Go Language (also known as Golang) is a statically typed, compiled programming l...
Go language basics introduction
Published: 2025-07-24 (a year ago)
GO

! [go] (https://pic2.zhimg.com/v2-55a9aba97d1e214f849ab2e55f3dabff_1440w.jpg?source=172ae18b)

Go Language Basics Introduction: From Grammar to Core Concepts

Go Language (also known as Golang) is a statically typed, compiled programming language developed by Google, which has risen rapidly in cloud-native, back-end development, and other fields since its official release in 2009 with its concise syntax, efficient performance, and strong concurrency support. This article will systematically introduce the basics of the Go language and help beginners quickly grasp the core syntax and programming ideas of this language.

1. Characteristics and advantages of Go language

The Go language is designed to incorporate the advantages of multiple programming languages while avoiding the complex features of traditional languages, and its core features include:

  • Concise and easy to learn: The grammar is refined, removing redundant grammatical elements (such as no class inheritance, generic early support, etc.), reducing learning costs

  • Static Type: Compile-time type checking to reduce runtime errors and improve code robustness

  • Fast Compilation: Compile faster than C++ and Java, supporting cross-platform compilation (compile once, run anywhere)

Native Concurrency: Implements lightweight concurrency with goroutines and channels, simplifying concurrent programming complexity

  • Memory Security: Built-in garbage collection mechanism, eliminating the need to manually manage memory

  • Rich Standard Library: Basic functions such as networking, IO, and encryption are used out of the box, avoiding reinventing wheels

2. Environment construction and the first program

Install the Go environment

  1. Go to Go OfficialParty DownloadPage and select the corresponding installation package according to the operating system

  2. After the installation is complete, open the terminal and perform 'go version' to verify that the installation is successful:

Copy
Go version go1.21.0 darwin/amd64 # output example

Writing fuck World

Create a 'hello.go' file and enter the following code:

Go Copy
package main // declare the main package (the executable must be in the main package)

import "fmt" // Import the FMT package of the standard library (for input and output)

func main() { // program entry function (must be main)

    fmt. Println("fuck, world!")  Print the string and wrap the line

}

Running Program:

shell Copy
go run hello.go # run directly

\# or compile and then run

go build hello.go

./hello  # Linux/Mac

hello.exe  # Windows

Output:

Copy
Hello, Go!

3. Basic grammar elements

Variables vs. Constants

There are many ways to declare variables in the Go language, the most commonly used are the 'var' keyword and the short variable declarer ':=':

Go Copy
package main

import "fmt"

func main() {

    // 1. Full declaration (specify type)

    var age int = 25

    // 2. Type inference (omitting types, inferred by assignments)

    var name = "GoLang"

    // 3. Short variable declaration (available within functions, auto-inferred type)

    score := 95.5

    

    fmt. Printf("age:%d,name:%s,score:%.1f\n", age, name, score)

    

    Constant declaration (use the const keyword, the value cannot be modified)

    const pi = 3.14159

    fmt. Println("pi:", pi)

}

Note: Short variables declare ':=' only within a function and at least one new variable must be declared.

Data Types

Go provides a wealth of data types, which can be divided into basic and compound types:

  1. Basic Types:
  • Integer: 'int' (varies with the number of digits in the system), 'int8'/'int16'/'int32'/'int64' (fixed length)

  • Floating-point numbers: 'float32' (single precision), 'float64' (double precision, default)

  • Boolean: 'bool'('true'/'false')

  • String: 'string' (immutable sequence)

  1. Composite Type:
  • Array: '[n]T' (fixed length collection of elements of the same type)

  • Slice: '[]T' (dynamically length sequence, more commonly used)

  • Mapping: 'map[K]V' (key-value pair set)

  • Struct: 'struct' (custom compound type)

Example:

Go Copy
Array (fixed length)

var nums \[3]int = \[3]int{1, 2, 3}

Slice (dynamic length)

scores := \[]float64{90.5, 88.0, 95.5}

Mapping (key-value pairs)

user := map\[string]string{

    "name": "Zhang San",

    "city": "Beijing",

}

Control flow statements

Conditional Statements (if-else)

Go Copy
func main() {

    score := 85

    If is followed by no parentheses, the conditional body must wrap and indent

    if score >= 90 {

        fmt. Println ("Excellent")

    } else if score >= 60 {

        fmt. Println("pass")

    } else {

        fmt. Println ("fail")

    }

    

    Special usage: You can add an initialization statement before the condition

    if age := 18; age >= 18 {

        fmt. Println ("Adult")

    }

}

Circular Statement (for)

The Go language only has a loop structure called 'for', but it can implement a variety of loop methods:

Go Copy
func main() {

    // 1. Basic for loop (similar to C)

    for i := 0; i < 5; i++ {

        fmt. Print(i, " ")

    }

    fmt. Println()

    

    // 2. Similar to a while loop

    count := 0

    for count < 3 {

        fmt. Println("Cycles:", count)

        count++

    }

    

    // 3. Infinite loop (requires break to exit)

    sum := 0

    for {

        sum += 10

        if sum >= 50 {

            break // Exit the loop

        }

    }

    fmt. Println("sum:", sum)

}
``` Go

#### Branch Statement (Switch)

Go's switch is more flexible than other languages and supports arbitrary comparisons:



``` Go
func main() {

    day := 3

    Auto-break, no need to add explicitly

    switch day {

    case 1:

        fmt. Println ("Monday")

    case 2:

        fmt. Println ("Tuesday")

    case 3:

        fmt. Println ("Wednesday")

    default:

        fmt. Println ("Other Weeks")

    }

    

    Multi-condition matching

    score := 88

    switch {

    case score >= 90:

        fmt. Println("A")

    case score >= 80:

        fmt. Println("B")

    default:

        fmt. Println("C")

    }

}

4. Functions and packages

Function definition and calling

Functions are the basic units of execution of the Go language, defined in the following format:

Go Copy
Function declaration: func function name (parameter list) return value type { function body }

func add(a int, b int) int {

    return a + b

}

Simplified parameter types (the same type of parameters can be merged)

func multiply(x, y float64) float64 {

    return x \* y

}

Multiple return values (Go language feature)

func divide(dividend, divisor float64) (float64, error) {

    if divisor == 0 {

        return 0, fmt. Errorf("Divisor cannot be 0")

    }

    return dividend / divisor, nil

}

func main() {

    sum := add(3, 5)

    fmt. Println("and:", sum)

    

    product := multiply(2.5, 4)

    fmt. Println("product:", product)

    

    result, err := divide(10, 2)

    if err != nil {

        fmt. Println("Error:", err)

    } else {

        fmt. Println("Quotient:", result)

    }

}

Package management

The Go language organizes code through packages, and each Go file belongs to a package:

  • Package Statement: The 'package name' in the first line of the document specifies the package to which it belongs

Import package: Import other packages using the 'import' statement, such as 'import "fmt"'

  • Visibility: The first letter of the variable / function name is uppercase for public (accessible by other packages), and lowercase for private

Example project structure:

Copy
myproject/

├── main.go # Package Main

└── mathutil/

    └── calculator.go # Package Mathutil

'calculator.go' content:

Go Copy
package mathutil

Public functions (capitalization)

func Add(a, b int) int {

    return a + b

}

Private function (lowercase, visible only in the package)

func subtract(x, y int) int {

    return x - y

}

'main.go' call:

Copy
package main

import (

    "fmt"

    "myproject/mathutil" // Import custom packages

)

func main() {

    total := mathutil. Add(10, 20)

    fmt. Println("Sum:", total)

}

5. Structs and interfaces

Struct

The struct is used to define custom compound types, combining fields of different types:

Copy
package main

import "fmt"

Define structs

type Person struct {

    Name string // public field

    Age int // public field

    addr string // private field (in-package access only)

}

Struct methods (functions bound to structs)

func (p Person) Introduce() string {

    return fmt. Sprintf ("My name is %s, and I'm %d this year", p.Name, p.Age)

}

Pointer Receiver (modify struct content)

func (p \*Person) Grow() {

    p.Age++

}

func main() {

    Create a struct instance

    person := Person{

        Name: "Zhang San",

        Age:  28,

    }

    

    fmt. Println(person. Introduce()) // call method

    person. Grow() // Age

    fmt. Println("One year later:", person. Introduce())

}

Interface

The interface defines a set of method signatures that implement the type of method that is "implicit" without the implementation details:

Copy
package main

import "fmt"

Defining Interfaces (Method Collections)

type Speaker interface {

    Speak() string

}

Implement type 1 of the interface

type Dog struct{}

func (d Dog) Speak() string {

    return "Whoa"

}

Implement type 2 of the interface

type Cat struct{}

func (c Cat) Speak() string {

    return "Meow Meow"

}

Receive interface type parameters

func makeSound(s Speaker) {

    fmt. Println(s.Speak())

}

func main() {

    var animal Speaker

    animal = Dog{}

    makeSound(animal) // Output: Wow

    

    animal = Cat{}

    makeSound(animal) // Output: Meow Meow Meow

}

Interfaces are the core mechanism of the Go language to implement polymorphism, which greatly improves the flexibility and scalability of the code.

6. Concurrent programming basics

One of the most important features of the Go language is the concurrency model, which enables lightweight concurrency through goroutines and channels:

Goroutine

Goroutines are lightweight threads specific to the Go language, managed by the Go runtime, and are extremely cheap to create:

Copy
package main

import (

    "fmt"

    "time"

)

Functions that are executed concurrently

func printNumbers() {

    for i := 0; i < 5; i++ {

        time. Sleep(100 \* time. Millisecond) // Simulate time-consuming operations

        fmt. Printf("%d ", i)

    }

}

func printLetters() {

    for c := 'a'; c < 'f'; c++ {

        time. Sleep(150 \* time. Millisecond)

        fmt. Printf("%c ", c)

    }

}

func main() {

    Start two goroutines (preceded by the go keyword)

    go printNumbers()

    go printLetters()

    

    The main goroutine waits for the sub-goroutine to complete (sync. WaitGroup)

    time. Sleep(2 \* time. Second)

    fmt. Println("\nEnd of Program")

}

Run results (in different order, reflecting concurrency):

Copy
0 a 1 b 2 c 3 d 4 e 

End of the procedure

Channel

Channel is used for communication between goroutines to achieve data synchronization:

Copy
package main

import "fmt"

Send data to the channel

func sendData(ch chan<- int) {

    for i := 1; i <= 5; i++ {

        ch <- i // Send data to the channel

    }

    close(ch) // Closes the channel

}

Receive data from the channel

func receiveData(ch <-chan int, done chan<- bool) {

    for num := range ch { // loop until the channel is closed

        fmt. Println("Received data:", num)

    }

    done <- true // Notifies completion

}

func main() {

    Create a channel (specify element type)

    dataChan := make(chan int)

    doneChan := make(chan bool)

    

    Start goroutine

    go sendData(dataChan)

    go receiveData(dataChan, doneChan)

    

    Wait for the receipt to complete

    <-doneChan

    fmt. Println ("All data processed")

}

7. Error handling

The Go language has no exception mechanism and explicitly handles errors by returning values:

Copy
package main

import (

    "errors"

    "fmt"

)

Returns the wrong function

func divide(a, b float64) (float64, error) {

    if b == 0 {

        Return a custom error

        return 0, errors. New("Divisor cannot be zero")

    }

    return a / b, nil // error nil when successful

}

func main() {

    result, err := divide(10, 2)

    if err != nil { // Check for errors

        fmt. Println("Error occurred:", err)

    } else {

        fmt. Println("result:", result)

    }

    

    Examples of errors

    result, err = divide(5, 0)

    if err != nil {

        fmt. Println("Error occurred:", err)

    }

}

8. Summary and advanced direction

This article introduces the basic syntax of the Go language, including core concepts such as variable declarations, data types, control flows, functions, structs, interfaces, and concurrency. To truly master the Go language, you also need to study the following in depth:

  • Detailed explanation of standard libraries (common packages such as 'net/http' and 'encoding/json')

  • Concurrency mode ('sync' package, goroutine pool, select statement)

  • Memory management and performance optimization

  • Testing & Performance Analysis ('Go Test', 'Pprof')

  • Actual project development (web service, tool development, etc.)

The Go language, with its simple and efficient characteristics, is particularly suitable for building high-performance backend services and cloud-native applications. Through continuous practice, you will gradually appreciate the unique charm of this language.

For further learning, you can visit [Go Official Documentation] (https://golang.org/doc/) or read classic books such as "The Go Programming Language".