Basic Syntax of Go

Time:2023-11-23

summarize

In the previous section, we introduced our first Go program, including: installing the Go environment, writing our first Go program, compiling and running the program, and so on. In this section, we will introduce the basic syntax of Go. Go is a concise and elegant language with some special syntax rules of its own. Therefore, it is necessary to familiarize yourself with the basic syntax of Go before introducing the knowledge about Go programming.

As of October 2023, the latest version of Go is 1.21, and this column will present knowledge using Go 1.21 syntax.

identifiers

In Go language, identifiers are names used to name variables, functions, structures, interfaces, and other program elements. Here are some of the requirements for identifiers in Go language.

1. Identifiers must begin with a letter (a-z or A-Z) or an underscore (_).

2. The identifier can be followed by letters, numbers (0-9) or underscores.

3. Identifiers are case-sensitive, which means that variable x and variable X are treated as two different identifiers.

4, can not use the Go language keywords as identifiers, such as: break, case, const, continue and so on.

5. The naming of identifiers should be descriptive and clearly express their use and meaning; good naming can improve the readability and maintainability of the code.

6. Try to avoid using single characters as identifiers, especially variable names; single character variable names may result in less readable code.

7. In different scopes, try to avoid using identifiers with the same name to ensure code consistency and accuracy.

Here are some invalid identifiers: 1name (starts with a number), case (Go language keyword), i+j (+ is a disallowed character).

Keywords.

Keywords are predefined special identifiers used to represent specific concepts or syntactic structures in a program. There are 25 keywords, namely: break, default, func, interface, select, case, defer, go, map, struct, chan, else, goto, package, switch, const, fallthrough, if, range, type, continue, for, import, return, var.

line separator

In Go, line separators are usually indicated by line breaks, not semicolons.Go, unlike some other programming languages (e.g., C/C++, Java, etc.), does not require a semicolon at the end of each line of code to indicate the end of a statement. The end of each statement is recognized by a natural line break, which means that when you enter a line break in your code, the Go compiler assumes that the statement has ended.

In the following sample code, fmt.Println statement does not use a semicolon to separate, but through the natural line breaks to separate the different statements.

package main

import "fmt"

func main() {
    fmt.Println("Hello")
    fmt.Println("")
}

Of course, if you need to write multiple statements on the same line, you must use a semicolon to make an artificial distinction. However, in actual development, we do not encourage this practice.

package main

import "fmt"

func main() {
    fmt.Println("Hello");fmt.Println("")
}

The var keyword

In the Go language, var is a keyword used to declare one or more variables. Using the var keyword you can declare different types of variables and you can specify the initial value of the variable.

The following is the basic syntax for declaring a variable using var:

                  var Variable Name Type

In the following sample code, we declare a variable of integer type.

package main

import "fmt"

func main() {
    var a int
}

Variables can be initialized at the same time they are declared, and if an initial value is specified for the variable, the type can be omitted and the compiler will automatically infer the type of the variable based on the initial value. Of course, it is also possible to declare more than one variable at a time, just separate them with commas.

package main

import "fmt"

func main() {
    var a int = 66
    var b = 88
    var c, d string
    c = "Hello"
    d = ""
    // Output: 66 88 Hello 
    fmt.Println(a, b, c, d)
}

Note: Declared variables and imported packages that are not used will result in compilation errors, which helps to improve the cleanliness and readability of the code.

The := operator

In the Go language, := is a special operator for declaring variables and initializing their values; it is called the short variable declaration operator. The declaration and initialization of a variable can be done at the same time using the := operator, which will infer the type of the variable based on the expression on the right hand side and assign the value of that type to the variable.

In the following sample code, the variable a is declared as an integer type and initialized to 66.

package main

import "fmt"

func main() {
    a := 66
    fmt.Println(a);
}

Note that the variable to the left of the = operator should not have been declared, or a compilation error will result.

blank space

In the Go language, spaces are commonly used to separate identifiers, keywords, operators, etc., and are used to improve the readability of code.

The Go language uses spaces for indenting code blocks, usually using 4 spaces as an indentation level. This is an important part of code formatting in the Go language to distinguish between different blocks of code.

package main

import "fmt"

func main() {
    a := 6
    if a > 0 {
        fmt.Println("positive")
    } else {
        fmt.Println("zero or negative")
    }
}

Using spaces between variables and operators, on both sides of operators, between function parameters, and in other scenarios can greatly increase the readability of your code.

package main

import "fmt"

func add(a, b int) int {
    return a + b
}

func main() {
    a := 66
    b := 99
    c := add(a, b)
    fmt.Println(c)    
}

Note: The use of spaces can improve the readability and clarity of your code, but overuse of spaces may make the code look too distracting. Therefore, you should keep your use of spaces in moderation and follow good coding style and norms.

marginal notes

In the Go language, comments are a way of adding descriptions and explanations to code that do not affect the execution of the program.The Go language supports two types of comments: single-line comments and multi-line comments.

Single line comments begin with a double slash (//) and can be followed by the contents of the comment. Single-line comments can occupy a separate line or appear at the end of a line of code.

// This is note 1
a := 66
b := 99 // This is comment 2

Multi-line comments begin with /* and end with */, can contain multiple lines of text, and are often used to illustrate the purpose and behavior of blocks of code such as functions and structures.

/*
    Multi-line comments on the first line
    Multi-line comments on the second line
*/
a := 66

package

In the Go language, packages are used to organize code and provide namespaces. A package can contain multiple Go source files and can be customized or from the standard library. By using the package keyword, related code files can be grouped together to form a single module. Each Go source file must belong to a package, and each package can contain one or more Go source files.

In the following sample code, we declare that the test.go file belongs to the main package. in the main package, we import the fmt package and use the fmt.Println function to print a message.

// test.go  
package main

import "fmt"

func main() {
    fmt.Println("Hello, ")
}

By organizing related code files in the same package, you can ensure that naming conflicts between them are minimized and that they can be easily referenced and used elsewhere.

import

In the Go language, the import keyword is used to bring in external dependency packages in order to use the functions, types, variables, etc. that they provide in your program. To import a package using import, specify the full name of the package and use the symbol . to specify the directory where the imported package is located. For example: to import the fmt package from the standard library, use the following statement: import “fmt”. This will introduce the fmt package into the program and make the functions and types available in it.

You can also use an alias to specify a custom name for the imported package. After specifying the alias, you can use the alias to call the functions in the package. For example: to import the fmt package as my_fmt, you can refer to the following sample code.

package main

import my_fmt "fmt"

func main() {
    my_fmt.Println("Hello, ")
}

input and output

In the Go language, input and output are handled through the fmt package in the standard library, which provides a number of functions for formatting input and output. To implement input and output, you can use the fmt.Scan or fmt.Scanln functions to read input from the standard input (usually the keyboard) and use the fmt.Print or fmt.Println functions to write output to the standard output (usually the screen).

In the following sample code, we first declare two variables name and age, which are used to save the name and age entered by the user. Then, use fmt.Print function to prompt the user to enter the name and age, and use fmt.Scanln function to read the user’s input. Finally, the user’s input is formatted and output to standard output using the fmt.Printf function.

package main

import "fmt"

func main() {
    var name string
    fmt.Print("Please enter your name:")
    // Read names from standard input
    fmt.Scanln(&name)

    var age int
    fmt.Print("Please enter your age:")
    // Read age from standard input
    fmt.Scanln(&age)
  
    // Output information to standard output
    fmt.Printf("Welcome %s, you are %d years old. \n", name, age)  
}

Note: In the above sample code, we have used the & symbol to pass the address of the variable to the Scanln function. This is because the Scanln function needs to access the variable’s memory address to update the variable’s value.

operator (computing)

The Go language supports the following operators.

Arithmetic operators: + (addition), – (subtraction), * (multiplication), / (division), % (modulo).

Assignment operators: = (assign), += (add equals), -= (subtract equals), *= (multiply equals), /= (divide equals), %= (modulo equals).

Comparison operators: == (equal to), ! = (not equal), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to).

Logical operators: && (logical and), || (logical or), ! (logical not).

Bitwise operators: & (bitwise AND), | (bitwise OR), ^ (bitwise DIFFERENT OR), ~ (bitwise INVERT), << (left shift), >> (right shift).

Pointer operators: & (takes the address of a variable and returns a pointer to the variable), * (dereferences a pointer).

Parenthesis operator: () (parenthesis operator, used to change the order of operations).

Type operators: typeOf (type lookup operator), sizeof (size lookup operator).

Null operator: nil (null operator, used to determine if a variable is null).

Error operator: error (error operator, used to determine if a variable is the wrong value).

Receive Operator: <- (Receive Operator for channel operations).

Indexing Operator: [] (indexing operator for accessing elements of types such as arrays, slices, maps, etc.).

Assertion operator: type . (value) (assertion operator for converting the value of an interface type to a concrete type).

Type conversion operator: type(value) (type conversion operator for converting a value of one type to another).

conditioned control

In the Go language, you can use if, else if, else for conditional judgment and execution control.

package main

import "fmt"

func main() {
  a := 66
  if a >= 88 {
    fmt.Println("Hello")
  } else if a > 50 && a < 88 {
    fmt.Println("")
  } else {
    fmt.Println("Other")
  }
}

You can also use the switch statement to execute different blocks of code according to different conditions, the basic syntax is as follows. The basic syntax is as follows. condition is a boolean expression, and value1, value2, etc. are the values to be compared. If the value of condition is equal to a certain value, the corresponding code block will be executed. If there is no matching value, you can choose to use the default block to perform the default operation.

switch condition {
case value1:
    // Execute the block when the condition is value1.
case value2:
    // Execute the block when the condition is value2.
...
default:
    // Default code block when execution condition is not met (optional)
}

In the following sample code, we use the switch statement to output the number of days in a given month.

package main

import "fmt"

func main() {
    month := 3
    switch month {
    case 1, 3, 5, 7, 8, 10:
        fmt.Println("31 days")
    case 4, 6, 9, 11:
        fmt.Println("30 days")
    case 2:
        fmt.Println("28 days or 29 days")
    default:
        fmt.Println("invalid month")
    }
}

Note: A single case can be followed by multiple values, separated by commas; when any of the multiple values is matched, the subsequent statements are executed.

circulate

In Go language, use for statement for loop control. Note: Unlike C/C++, Java and other languages, there is no while loop in Go language.

There are three forms of for loops: the first is the basic for loop, the second is the simplified for loop, and the last is the infinite loop.

The basic syntax of a for loop is as follows. Among them, initialization is the initialization statement before the start of the loop; condition is the loop condition, continue to execute the loop when the condition is satisfied; post is the post-processing statement after the completion of each loop execution.

for initialization; condition; post {
    // Loop body
}

In the following sample code, we use a basic for loop to calculate the sum of 1 to 100 added together.

package main

import "fmt"

func main() {
    sum := 0
    for i := 1; i <= 100; i++ {
        sum += i
    }

    fmt.Println(sum)
}

A simplified for loop has only a loop condition, no initialization statement and no post-processing statement. In the following sample code, we use a simplified for loop to calculate the sum of 1 to 100.

package main

import "fmt"

func main() {
    sum := 0
    i := 1
    for i <= 100 {
        sum += i
        i += 1
    }

    fmt.Println(sum)
}

Infinite loops can be used directly with the for keyword, without any other statements after it. In the following example code, we use an infinite loop to calculate the sum of 1 to 100.

package main

import "fmt"

func main() {
    sum := 0
    i := 1
    for {
        sum += i
        i += 1
        if i > 100 {
            break
        }
    }

    fmt.Println(sum)
}

Recommended Today

Resolved the Java. SQL. SQLNonTransientConnectionException: Could not create connection to the database server abnormal correctly solved

Resolved Java. SQL. SQLNonTransientConnectionException: Could not create connection to the database server abnormal correct solution, kiss measuring effective!!!!!! Article Catalog report an error problemSolutionscureexchanges report an error problem java.sql.SQLNonTransientConnectionException:Could not create connection to database server Solutions The error “java.sql.SQLNonTransientConnectionException:Could not create connection to database server” is usually caused by an inability to connect to the […]