Introduction to go language - (II) language structure

Zhou Zhaodong 2021-09-15 09:15:27
Let's take a look at one Go Language executable file contains which parts

Hello World example

Go The basic composition of language generally includes the following parts

  • Package declaration
  • Introduction package
  • function
  • Variable
  • sentence & expression
  • notes

    Instance analysis

    package main
    import "fmt"
    func main() {
    /* Go One of the first hello world */
    fmt.Printf("hello world !!!")

    Let's make a brief analysis here

  • package main Define package name . This must first know which package the file belongs to ,package main Represents a program that can be executed independently , Every Go All applications need to include a file named main My bag .
  • import "fmt" Is to import fml package ( Function of , Or other elements ).fmt Package implements formatting IO( Input / Output ) Function of .
  • func main() Is the function that the program starts to execute .main Function is a necessary part of every executable program , Generally speaking, it is the first function executed after startup ( If there is init() Function will execute the function first ).
  • /.../ It's a comment , Will be ignored during program execution .
  • fmt.Println(...) You can output strings to the console , And at the end automatically add the line feed character .


    Can pass Go Language provides go build perhaps go run Command to Go Language program to compile :

  • go build The order can change Go The language program code is compiled into binary executable files , But we need to run the binary manually ;
  • go run Orders are more convenient , It will run directly after compilation Go Language program , A temporary file will be generated during compilation , But the executable file will not be generated , This feature is very suitable for debugging programs .

    go build command

    go build Command to start compilation , It can be Go Language programs and related dependencies are compiled into an executable file , The syntax is as follows .

    go build fileName

    among fileName For the required parameters , Can be one or more Go The source file name ( When there are multiple parameters, you need to use spaces to separate two adjacent parameters ), You can also omit not to write .

    go run command

    Besides using go build Outside command ,Go Language also provides us with go run command ,go run Command combines compilation and execution instructions , Will be executed immediately after compilation Go Language program , But the executable file will not be generated .

go run The syntax of the command is as follows :

go run fileName

among fileName For the required parameters , Parameters must be the same main All source file names under the package , And can't be empty .

Personal blog address

Please bring the original link to reprint ,thank
Similar articles