1, newHello.go

package main

import "fmt"

func main(a) {
   fmt.Println("Hello World")}Copy the code

2, run,

You can type ingo run Hello.goRun directly

Or you can compile firstgo build Hello.goIn the run

3, explain

1.package main

  • Package name specifies the package location of the file. Default is the folder name of the file. For example, the package name of the test.go file is test.

  • The package name main does not mean that it is in the main folder, but it means that it is a main file, the main program of a project or module, which means that the source file can be compiled and run directly. It’s kind of the main entrance to go. One main program entry per project.

  • Unlike Java:

    In Java, any Java file can have a single main method as a startup function

    In go, any package can have a unique GO file with a main method

2.import "fmt"

  • Import packages
  • The above FMT is a standard library for the Go language. It actually loads the module into GOROOT
  • == Do not import packages that are not used. An error will be reported
  • Of course, the Go import also supports two ways to load self-written modules: relative pathsimport "./model"// The model directory in the same directory as the current file, but it is not recommended to import absolute pathsimport "shorturl/model"/ / load GOPATH/SRC/shorturl/model module

1. Packages usually use last-level paths to extract methods or variables:

import "xxx.com/go-qb/db"
Copy the code

Usage: db. (X)

2, If you want to rename the reference, add the alias name to the reference.

import mysql "xxx.com/go-qb/db"
Copy the code

Usage: mysql. (X)

3. If you don’t want to add a prefix, add a. Before the reference.

import . "xxx.com/go-qb/db"
Copy the code

Usage: (X)

3.func main()

  • There are two special functions in Golang,

    func main

    func init

  • The main function needs no introduction. It is the same in all languages. As an entry point to a program, there can only be one.

  • The init function is optional, optional, or even multiple (although one init function within a package is strongly recommended) in each package. The init function is automatically called when you import the package. So the init function doesn’t need to be called manually,l plus it will only be called once, because when a package is referenced multiple times, it will only be imported once

  • =={} must follow () without line breaks, which is enforced by Go

4.fmt.Println("Hello World")

  • = =PrintlnUppercase, not lowercase, for reasons that we’ll talk about in the next chapter

Just like in C

printf("Hello World");
Copy the code

Similar to C++

cout<<"Hello World"<<endl;
Copy the code

Similar to Java

System.out.println("Hello World");
Copy the code

Similar to Python or Lua

print("Hello World");
Copy the code

Personal view

  • Why is the function keyfuncWhy not write it allfunctionOr likePythonasdef(The Google founder actually contributed the keyword.)