Table of contents
2. Description of grammar words
1. Go program executes commands
Non-obligatory coding style recommendations:
1. Hello program explanation
Go Hello World example
The basic composition of the Go language has the following parts:
• package declaration
• import package
• function
• variables
• Statements & Expressions
• Notes
Next let's look at the simple code test.go, which prints "Hello World!":
package main import "fmt" func main() { /* This is my first simple program */ // I am a single-line comment fmt.Println("Hello, World!") }
Let's look at the various parts of the above program:
1. The first line of code package main defines the package name . You must have the first non-commented line in the source file
specified
Which package this file belongs to, such as: package main. package main represents a program that can be executed independently,
Every Go application consists of a package named main.
path to go
2. The next line import "fmt" tells the Go compiler that this program needs to use the fmt package (functions,
or other elements),
The fmt package implements functions for formatting IO (input/output).
3. The next line func main() is the entry function for the program to start executing. The main function must be included in every executable program. Generally speaking, it is the first function to be executed after startup (if there is an init() function, it will be executed first).
4. The next line /*...*/ is a comment and will be ignored during program execution. Single-line comments are the most common form of comments, and you can use single-line comments starting with // anywhere . Multi-line comments are also called block comments , which start with /* and end with */,
And it cannot be nested. Multi-line comments are generally used for package documentation descriptions or code snippets that are commented into blocks.
5. The next line fmt.Println(...) can output the string to the console terminal , and automatically add the newline character \n at the end.
The same result can be obtained using fmt.Print("hello, world\n").
The two functions Print and Println also support the use of variables, such as: fmt.Println(arr). If not specified, they output the variable arr to the console in the default print format.
6. When an identifier (including constants, variables, types, function names, structure fields, etc.) starts with an uppercase letter,
Such as: Group1, then the object using this form of identifier can be used by the code of the external package (the client program needs to import this package first), which is called export (like public in object-oriented language);
Identifiers that start with a lowercase letter are not visible outside the package, but they are visible and available throughout the package (like private in object-oriented languages).
2. Description of grammar words
line separator
In a Go program, a line represents the end of a statement.
Each statement does not need to end with a semicolon; like other languages in the C family, because these jobs will be done automatically by the compiler.
If you plan to write multiple statements on the same line , they must use ;
note
Comments are not compiled, each package should have related comments.
Single-line comments are the most common form of comments, and you can use single-line comments starting with // anywhere.
Multi-line comments are also called block comments, which start with /* and end with */.
identifier
Identifiers are used to name program entities such as variables and types.
An identifier is actually a sequence of one or more letters (A~Z and a~z) numbers (0~9) and underscore_,
But the first character cannot be a number, only letters or underscores.
"_" is called an empty identifier , and is generally used in variable declarations and package imports, such as in Go language programs,
If there is an unused variable, an error will be reported at compile time, because the Go language requires the existence of entities
must use,
So you can add code like _=a, so that the Go language compiler will think that it will not report if it is used
Wrong, it doesn't actually do anything to the variable a. Identifiers are freed after program initialization
Identifiers begin with a letter (both uppercase and lowercase) or an underscore, and may be followed by multiple letters, underscores, and
number. The Go language does not allow the use of punctuation marks in identifiers, such as a series of symbols such as @, $, %, etc.
Although the upper and lower case letters are acceptable, the Go language is a case-sensitive programming language, so
Test
The test Go language program represents two different identifiers
keywords:
3. Basic programming concepts
1. Go program executes commands
go build
The Go language is a compiled static language, so before running the Go language program, it must be compiled into a binary
executable file.
Generally, the Go language code is written in the editor, and then the Go build or go run command provided by the Go language is used to run the Go language code.
Language program to compile:
The go build command is used to start the compilation, which can compile the Go language program and related dependencies into an executable file
, its syntax is as follows.
go build fileName
Where fileName is the required parameter, which can be one or more Go source file names (when there are multiple parameters
When you need to use a space to separate two adjacent parameters), you can also omit it.
When using the go build command to compile, the target file is only compiled but not executed, and the execution results of different parameters are also different.
the same.
1) When the parameter is not empty
If fileName is the name of all source files under the same main package (there may be one or more), the compiler
will generate a
Executable files with the same name as fileName (such as executing go build abc.go def.go ... will generate an abc.exe
document);
If fileName is the source file name of a non-main package, the compiler will only check the syntax of the package without generating
into an executable file.
If you need to specify the output executable file name, you can use the -o parameter, see the following example:
go build -o myexec main.go lib.go
2) When the parameter is empty
If the main package exists in the current directory, a "directory name.exe" executable with the same name as the current directory name will be generated
line file (for example, when the go build command is executed in the hello directory, the hello.exe file will be generated); if there is no main package, only the syntax check will be performed on the program source code in the current directory, and no executable file will be generated.
For example, there are two files lib.go and main.go in the current directory. If go build starts compiling, it will search the go source code in the current directory, and go build will find the two files lib.go and main.go.
After compiling these two files, an executable file with the name of the current directory is generated and placed in the current directory.
Case: two files main.go and lib.go are in the same folder (gobuild)
The main.go code is as follows:
package main
import (
"fmt"
)
func main() {
pkgFunc() //外部函数调用
fmt.Println("hello worlds")
}
The lib.go code is as follows:
package main
import "fmt"
func pkgFunc() {
fmt.Println("call pakFunc")
}
Enter the compilation command line as follows:
go build
Enter the execution command line as follows:
./gobuild
The result of the operation is as follows:
call pakFunc
hello worlds
Other methods:
$ go build main.go lib.go
$ ls
lib.go main main.go
$ ./main
call pkgFunc
hello world
$ go build -o myexec main.go lib.go
$ ls
lib.go main.go myexec
$ ./myexec
call pkgFunc
hello world
go run command
In addition to using the go build command, the Go language also provides us with the go run command, which will compile and execute
Combining two commands into one,
The Go language program will be executed immediately after compilation, but no executable file will be generated.
The syntax format of the go run command is as follows:
go run fileName
Among them, fileName is the required parameter (file), and the parameter must be all source file names under the same main package, and cannot be empty.
for example:
$go run demo.go
Hello World!
You can see that after the go run command on line 1 is executed, the running result of the program is directly output on line 2.
Case: hello.go code is as follows
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("args:", os.Args)
}
$go run hello.go --filename xxx.go
Revise:
go install command
Command format: go install [optional parameters].
Command function: compile and install source files and software packages, that is, install the compiled files (executable binary files) into the specified directory.
Special instructions: Install compiled files (executable binaries, archives, etc.) into the specified directory.
If the environment variable GOBIN is set, move the binary executable to this directory.
If Go modules are disabled, put them under $GOPATH/pkg/$GOOS_$GOARCH.
Implementation steps:
1.whereis demo....Check if there is a program named -demo in the current system
2. Start writing the demo.go source code file
3. Test whether the function is feasible in the current directory
4. Check whether the environment of the current terminal is configured normally
If not set manually
Make sure the target program has write permission
sudo chmod 0777 /usr /local/bin
5. Compile and install the class execution program in the current directory
go install -x demo.go
......
6. Verify that goinstall is successful
direct demo
7. Clean up the environment and restore the target directory files
To use install first make sure the following things are off
export GO111MODULE="off"
sudo chmod 0777 /usr/local/bin
go install -x main.go
After entering go install -x main.go
will output:
...
mkdir -p /Users/ucwords/go/bin/
...
mv $WORK/b001/exe/a.out /Users/ucwords/go/bin/target directory (directory name of go modules)
rm -r $WORK/b001/
Last View:
If it says that GOBIN is not set, use the following command to specify:
Temporary: export GOBIN="/usr/local/go/bin"
permanent:
sudo vim ~/.bashrc
export GOBIN=/usr/local/bin
save and exit
source ~/.bashrc
verify:
go env can verify whether the current command is in effect
delete:
sudo rm /usr/local/bin/main
=================================================================
go build+包
There is a file (main.go) and a folder (mypkg) in a folder (goinstall).
There is a file (mypkg.go) in a folder (mypkg).
The main.go code is as follows:
package main
import (
"fmt"
"goinstall/mypkg"
)
func main() {
mypkg.CustomPkgFunc()
fmt.Println("hello world")
}
The mypkg.go code is as follows:
package mypkg //建议当前包名和所在目录一致
import "fmt"
func CustomPkgFunc() {
fmt.Println("call CustomPkgFunc")
}
Execute the following command to compile the goinstall code by package:
$ go build -o main goinstall
$ ls
main main.go mypkg
$ ./main
call CustomPkgFunc
hello world
If there is an error like
method:
go env ⇒ gopath ==>/home/caoqb/go
cp goinstall /home/caoqb/go/src/ -r
cd /home/caoqb/go/src
go build -o main goinstall
./main verification effect
4. Go coding specification
"The code must be written in accordance with the principle of being written for humans to read, but only for machines to execute."
=========" This passage comes from "Computer Programming and Interpretation"
Coding style is a human-related, machine-independent issue. The quality of the code style does not affect the work of the compiler.
However, it affects team collaboration, code reuse, evolution, and defect repair.
The Go language is likely to be the first language that enforces a unified code style. Some problems that are completely ignored by compilers in other languages will be considered compilation errors before the Go compiler. For example, if the curly braces are placed on a new line, you will see a striking compilation error.
This will make many people feel incredible. Love it or hate it, unlike other coding conventions alone you can write
compared to the language of a book,
There is no doubt that this approach of the Go language simplifies the problem. Next, we will introduce the coding specification of the Go language.
Mainly divided into two categories, namely: the coding specification enforced by the Go compiler
Non-enforceable coding style recommendations enforced by Gotool.
Mandatory Coding Standards:
The coding specification enforced by the Go compiler is also the Go language designer's opinion that a unified code style is most needed.
1. Naming
Naming rules involve the naming of variables, constants, global functions, structures, interfaces, methods, etc. Go language from the grammar layer
The following restrictions are made:
Any name that needs to be exposed to the outside world must start with a capital letter, and any name that does not need to be exposed to the outside world should start with a lowercase letter
head.
It can only be composed of numbers, English letters, underscores, cannot start with a number, and cannot conflict with keywords.
The two most popular nomenclature in the software development industry are
Camel notation (similar to DoSomething and doSomething)
Underline method (corresponding to do_something)
The Go language clearly declares that it supports the camel naming method and rejects the underscore method. Camel naming is officially supported and recommended in Java and C#,
The underscore nomenclature is mainly used in the world of C language, such as Linux kernel and driver development. When you start programming in Go language, forget about underscores and avoid writing nondescript names.
2. Arrange
The Go language even performs syntax-level checks on the way the code is arranged, agreeing on the clear placement of curly braces in the code block. The following first lists a wrong way of writing:
// typo
func Foo(a, b int)(ret int, err error)
{
if a > b
{
ret = a
}
else
{
ret = b
}
}
This way of writing is most familiar to many programmers who grew up in the arms of Microsoft, but there will be compilation errors in the Go language
$ go run hello.go
# command-line-arguments
./hello.go:9: syntax error: unexpected semicolon or newline before {
./hello.go:18: non-declaration statement outside function body
./hello.go:19: syntax error: unexpected }
As you can guess from the above error message, there is a problem with the position of the left curly brace {. Let's adjust the code above:
// Correct spelling
func Foo(a, b int)(ret int, err error) {
if a > b {
ret = a
} else {
ret = b
}
}
As you can see, the else must even immediately follow the previous closing curly brace } and cannot wrap. This rule of the Go language basically guarantees that the logical structure of all Go codes is completely consistent, and there will be no more cleanliness programmers who have to adjust the positions of all curly braces before maintaining other people's code. question.
Non-obligatory coding style recommendations:
package main
import "fmt"
func Foo(a, b int)(ret int, err error){
if a > b {
return a
return 0, nil
}
}
func
main() { i, _ := Foo(1, 2)
fmt.Println("Hello, world", i)}
This code can compile and run normally, but it is ugly and unbearable. Now we use the formatting function in Gotool to beautify it (assuming the above code is saved as hello.go)
$ go fmt hello.go
hello.go
After executing this command, the hello1.go file will be updated. At this time, open hello1.go again and look at the code with a new look. You can see that the formatting tool has done many things:
1. Adjusted the position of each statement
2. Reposition the curly braces
3. Indent code with tabs
4. Add spaces
Of course, the formatting tool doesn't know how to help you improve the naming, so don't be too demanding.
This tool can not only format one file at a time. For example, if you run go fmt directly without any parameters, you can directly format all *.go files in the current directory, or you can also specify a package name that can be found in GOPATH.
It's just that we don't really recommend using this tool. After all, maintaining good coding style should be the first step in writing
Noticed it while coding. The first time it is written in a way that conforms to the specification, there will be no need to consider how to beautify it in the future.
Introduction to gofmt
The development team of the Go language has formulated a unified official code style, and launched the gofmt tool (gofmt or go
fmt)
To help developers format their code into a unified style.
gofmt is a cli program that reads standard input first. If a file path is passed in, it will format the file.
If a directory is passed in, all .go files in the directory will be formatted, if no parameter is passed, it will be formatted in the current directory
All .go files for .
gofmt does not simplify the code by default, use the -s parameter to enable the code simplification function, specifically, the following conversion will be performed:
go fmt use
go fmt -w xx.go
package main
import "fmt"
func main() {
a := 1
b := 2
c := a + b
fmt.Println(c)
}
Use the following rules to format the above code.
gofmt -w -r "a + b -> b + a" main.go
package main
import "fmt"
func main() {
a := 1
b := 2
c := b + a
fmt.Println(c)
}
Note: go fmt uses tabs to represent indentation, and there is no limit to the line width. If you manually wrap the code,
gofmt does not enforce formatting code back to one line.
-l display those files that need to be formatted
-w Write the rewritten content directly to the file instead of printing the result to standard output.
-r adds a rewrite rule of the form "a[b:len(a)]->a[b:]", which is convenient for us to do batch replacement.
The rule accepted by -r is pattern -> replacement, where pattern and replacement must be legal Go syntax, and single, lowercase characters will be used as wildcards.
The vim global replacement command is: :%s/source string/destination string/g
-s Simplify the code in the file
-d show the diff before and after formatting instead of writing to the file, the default is false
-e prints all syntax errors to standard output. If this flag is not used, only the first 10 errors on different lines will be printed
error.
-cpuprofile supports debug mode, write the corresponding cpufile to the specified file
5. Class practice questions
1. Write a basic "hello world" practice program.
2. Use go run go build go install to install programs in different ways
3. Use go fmt to format code exercises.