SoFunction
Updated on 2025-03-05

Deeply understand the basic syntax and common functions of Go language

1. Basic syntax

Identifier naming specification

Go is case-sensitive, and the naming of the identifier includes commands for variables, constants, functions, structures, interfaces and methods in Go. Go defines that any identifier that needs to be exposed must start with capital letters, and identifiers that do not need to be exposed must start with lowercase letters.

An identifier starts with capital, which means it can be referenced by external package code, called export. If you start with a lowercase letter, it is invisible to the outside, but is visible and available inside the entire package.

The naming of identifiers should avoid conflicts with keywords built into Go.

Command specification for variables

The camel nomenclature is adopted, and the first letter is controlled based on the access control of uppercase or lowercase.

var username string
var url string

Constant naming specifications

The names of constants are all composed of capital letters and are underscores to separate multiple words.

const JUEJIN_URL = ""

Enumerate constants

const (
    SUCCESS = "200"
    NOT_FOUND = "404"
    INTERAL_SERVER_ERROR = "500"
)

Naming specifications for structures

The structure also uses camel nomenclature, and the uppercase and uppercase letters of the first letter are determined based on access control.

type Info stuct {
    Username string
    Age int 
}

Interface naming specifications

The naming specification of an interface is basically the same as the naming specification of a structure. Only one method's interface name ends with "er", such as Fighter

type Fighter interface {
    fight(p []byte)(skill string, err error)
}

Naming specifications for files and packages

The naming of Go files and packages is composed of lowercase letters, which is short and meaningful. Note: Do not use underscores or camel naming for packages.

Common keywords in Go

Keywords illustrate
var Define variables
const Define constants
package Bag
import Import package keywords
func Define function keywords
return Used to modify the return value in the function
interface Define interface
struct Define abstract data types
type Declare a custom type
map Declare map data type
range Used for traversal
if、else、for、switch、break、case、continue、fallthrough、soto、default For process control

Comments in Go

Used in Go//To comment the code, use/* Multiple lines of code */Comment multiple lines of code

Definition and use of variables

There are many ways to define variables in Go, and keywords can be used.varDefine variables, or define multiple variables at once.

Use the var keyword to define variables

var variable_name variable_type = value

Declare multiple variables of the same type at once

var variable_name1, variable_name2 variable_type

Declare multiple variables of different types at once

var (
    variable_name1 variable_type
    variable_name2 variable_type
)

Define variables using := Custom judge variable types

name := "Tony"

Can be omittedvarKeywords

Create a new folder under the go-quickstart project, named "01-Basic Syntax", and create a new Go file under the folder

package main

import "fmt"

func main() {

   // Use the var keyword to define variables   var name string = "tony"
   (The value of the "name variable is:", name)

   // Use var to define multiple variables of the same type   var username, address, phone string
   username = "Tony"
   address = "NY"
   phone = "010-111222"
   (The values ​​of the three variables "name, address, and phone are:", username, address, phone)

   // Use var to define multiple variables of different types   var (
      user_name    string
      user_age     int
      user_balance float64
   )

   user_name = "tony"
   user_age = 40
   user_balance = 1000000.0
   (The values ​​of "user_name, user_age, user_balance are:", user_name, user_age, user_balance)

   // Define variables using automatic type inference   user_id := 1000
   (The value of the "user_id variable is:", user_id)
}

Execute the above code and the output result is as follows:

The value of the name variable is: tony
The values ​​of the three variables name, address, and phone are: Tony NY 010-111222
The values ​​of the three variables: tony 40 1e+06
The value of the user_id variable is: 1000

use:=Defining variables is the most commonly used way to define variables in Go, but variables defined in this way can only be used in local code blocks and cannot be used globally.

Define constants

Use of the definition of constantsconstKeywords, constants cannot be modified once they are defined

package main

import "fmt"

func main() {

   // Use the const keyword to define constants. Once defined, they cannot be modified.   const URL = ""

   ("The value of the constant URL is:", URL)

   // Define multiple constants at once   const (
      HOST = 3306
      APP  = "/go"
   )

   ("The values ​​of the two constants of HOST and APP are:", HOST, APP)

   // When defining a constant, if only the first constant is assigned and the subsequent constant is not assigned, the default value is equal to the value assigned by the first constant   const (
      NUM = 100
      COUNT
      QUANTITY
   )
   ("NUM,COUNT,QUANTITY values ​​are:", NUM, COUNT, QUANTITY)
}

Execute the above code and the output result is as follows:

The value of the constant URL is:
The values ​​of the two constants of HOST and APP are: 3306 /go
The values ​​of NUM, COUNT, QUANTITY are: 100 100 100

2. Common functions

main function and init function

main function

In the above code, all the code is written in usefuncKeyword definitionmainAmong functions, in Go, the main function is an entry function, similar to the main function in Java.

init function

The init function in Go is responsible for initializing the package, and the init function:

  • Execute before the main function, automatically call, initialize variables in the package, etc.
  • The init function cannot be called by other functions
  • Each package can have multiple init functions, and the execution order of the init function of the same package is related to the location of the init function definition.
  • Each source file in the package can also have multiple init functions
  • The init functions in different packages determine the execution order of the init functions according to the imported dependencies.
  • The init function does not return a value
// filename 

package main

import "fmt"

func init() {
   ("This is the first init function")
}

func init() {
   ("This is the second init function")
}

func init() {
   ("This is the third init function")
}

func main() {

   // Common functions   ("This is the main function")

}

Execute the above code, and the output is as follows:

This is the first init function
This is the second init function
This is the third init function
This is the main function

Call the location of the first and third init functions and execute the code again

This is the third init function
This is the first init function
This is the second init function
This is the main function

The order of execution of the init function in the same file is related to the location, but they will be executed before the main function.

init function VS main function

Both the main function and the init function cannot have any return value when defining, and they are automatically called by Go.

The main function can only define one, and the init function can define multiple.

These two functions can only be officially defined to be used in the test environment, and are not recommended for use in the production environment.

fmt package and its functions

In addition to the main function, the above code also involves printing related functions. These functions are all under the fmt package, and there are three output functions in total.

  • Println: Automatically wrap and output multiple values ​​at once, multiple values ​​will have spaces in the middle.
  • Print: No automatic wrapping, multiple values ​​are output continuously, no spaces
  • Printf: Format output
// filename 


package main

import "fmt"

func main() {

   // Common functions   name_01 := "tony1"
   name_02 := "tony2"
   name_03 := "tony3"
   ("Automatically wrap, there will be spaces between multiple values", name_01, name_02, name_03)
   ("No line wrapping, no spaces between multiple values", name_01, name_02, name_03)
   ("\n")
   ("%v, %v, %v format output", name_01, name_02, name_03)

}

Execute the above code and the output result is as follows:

Automatically wrap the line, there will be spaces between multiple values ​​tony1 tony2 tony3
There is no automatic wrapping, there will be spaces between multiple values ​​tony1tony2tony3
tony1, tony2, tony3 Format output

When formatting output%vIndicates the value of the obtaining variable.

The above is a detailed content of the basic grammar and commonly used functions of Go. For more information about Go syntax functions, please pay attention to my other related articles!