当前位置:网站首页>Go web programming practice (1) -- basic syntax of go language
Go web programming practice (1) -- basic syntax of go language
2022-07-02 21:02:00 【Li Yuanjing】
Catalog
Preface
I'm glad to learn from you Go Language , There are many scenes about it , Including cloud computing 、 Container virtualization 、 Distributed storage 、 Web crawler 、 Operations and development 、Web Development 、 Server development 、 Blockchain 、IoT And other fields .
today , Bloggers mainly introduce its basic practical grammar in detail , It is convenient for readers to quickly grasp Go Usage of language .
Hello World
Programmers have a Magical Law , That's it Hello World. Every time we learn a new programming language , Will touch it . and Go The first lesson of language , Also start with it .
package main
import "fmt"
func main() {
fmt.Println("Hello World")
}
The code is very simple , Those who have learned other languages should be easy to understand .
Package declaration and import
among ,package Is the keyword that declares the package name ,“main” It's the name of the bag , You can also customize .
Go Language pack , Has the following characteristics :
- The peer files in a directory belong to a package
- The package name can be different from its directory name
- main Bag is Go Language application entry package . One Go Language applications must have and only have one main package . If a program does not main package , Errors will be reported at compile time .
and import Is the keyword of the import package , Through it, we can reference variables or methods of other packages . It should be noted that , The package name must be in double quotation marks (“”) Surround .
If you want to import multiple packages , You can also write like this :
import(
"fmt"
"os"
)
/* names */
import(
fm "fmt"
li "os"
)
How to run the program
here , We can use the compiler GoLand function , You can also use the command line go run “go file name ” Perform console output .
Of course , We can also split , Run through the command line that compiles first and then executes Hello World. The code is as follows :
go build HelloWorld.go
./HelloWorld
Basic grammar
Go Program by keyword 、 identifier 、 Constant 、 character string 、 Symbols and other marks . Generally speaking , A line is a statement , But it's not like Java Other languages , You don't need to use it at the end “;” ending .
It should be noted that , If you will have more Go The statement is written on one line , Then we need to use “;” To separate . But the official does not recommend that we write like this , One sentence per line is the standard , And more readable .
notes
Go Language notes , In fact, with Java Language is as like as two peas. , There are also single line comments and multi line comments . among , A single line comment passes “//” Statement . Multiline comments through “/*” start ,"*/" ending . The specific code is as follows :
// Single-line comments
/* Multiline comment */
identifier
Identifiers are mainly used as variables 、 Type and other program entities . An identifier consists of one or more letters 、 Numbers 、 Underline ("_") form . It should be noted that , The first character cannot be a number and Go Program keywords .
Variable
stay Go In language , The declaration syntax of variables is as follows :
var name type
among ,var Is the keyword for declaring variables ,name Is a variable name. ,type It's the type of variable .
From here , Readers can see ,Go Language when declaring variables , Different from other languages , It puts the type after the variable name .
Of course , occasionally , It's too troublesome to declare variables one by one , You will also apply for a lot of variables at the same time . The code for declaring multiple variables is as follows :
var(
name string
age int
student string
)
except var Out of keywords , You can also use short variable definitions and initialization syntax , The format is as follows :
name := expression
// Example
name :="liyuanjing"
It should be noted that , Short mode has the following limitations :
- Can only be used to define variables , At the same time, it will be explicitly initialized
- Cannot provide data type
- Can only be used inside a function , That is, it cannot be used to declare global variables .
below , Bloggers directly use multiple examples , To explain how variables are assigned . The specific code is as follows :
// Complete grammar
var name string = "liyuanjing"
// Automatically identify the type
var name = "liyuanjing"
// Multivariable assignment declaration
var (
name string = "liyuanjing"
age int = 29
money float32 = 22.22
)
var name,age,money="liyuanjing",29,22.22
// Declaration of global variables
var global int=558
Special attention required , If you declare variables in a method , Then this variable must be used later , Otherwise, the program will report an error .( That is, don't use this value , It also reports mistakes )
Constant
stay Go In language , Constant usage const Make a statement , Constants are mainly used to store values that will not change . It should be noted that , Constants can only be Boolean 、 Numbers ( Integers 、 Floating point numbers and complex numbers )、 character string . Its syntax and usage are as follows :
// grammar
const Constant names [ type ]= Constant values
// Example
const name string="liyuanjing"
const age int=22
stay Go In language , Type specifiers can be omitted "[ type ]". Because the compiler can judge the type of a variable according to its value .
// Explicitly declare
const Pi float32=3.1415926
// Implicitly declare
const Pi =3.1415926
It should be noted that , The value of a constant must be determinable at compile time , The calculation process can be involved in its assignment expression . But all the values used for calculation , Must be available during compilation . such as 3/2 Can , But if os.GetEnv(‘url’) Calling method , No way. . Because the return result of the method call can only be known at run time .
Constant declarations can sometimes use constant generators iota initialization .iota Used to generate a set of constants initialized with similar rules , But you don't have to write an initialization expression every line .
Let's say in advance , stay Go In language , There is no enumeration type . We usually pass iota Implement enumeration types . such as , Now we need to define southeast, northwest 4 An enumeration type , Then it can be realized directly :
type Direction int
const(
North Direction=iota
East
South
West
)
As shown in the above code , Default North Namely 0, Then the constant of each value is automatically added 1.
Operator
seeing the name of a thing one thinks of its function , Like other languages, it is computation . below , Let's just give an example :
var a,b,c int=1,2,3
d :=a+b*c
Through the above code , We can easily calculate ,d be equal to 7.
边栏推荐
- qwb2018_ core kernel_ rop
- 【QT】QPushButton创建
- 7. Build native development environment
- Happy Lantern Festival! Tengyuanhu made you a bowl of hot dumplings!
- Volvo's first MPV is exposed! Comfortable and safe, equipped with 2.0T plug-in mixing system, it is worth first-class
- Share several map bed websites for everyone to share pictures
- Customized Huawei hg8546m restores Huawei's original interface
- [12] the water of the waves is clear, which can wash my tassel. The water of the waves is muddy, which can wash my feet
- Friends who firmly believe that human memory is stored in macromolecular substances, please take a look
- Analyze comp-206 advanced UNIX utils
猜你喜欢
Check the confession items of 6 yyds
I drew a Gu ailing with characters!
[error record] the command line creates an error pub get failed (server unavailable) -- attempting retry 1 in 1 second
[fluent] dart technique (independent main function entry | nullable type determination | default value setting)
[shutter] the shutter plug-in is used in the shutter project (shutter plug-in management platform | search shutter plug-in | install shutter plug-in | use shutter plug-in)
Burp install license key not recognized
Web3js method to obtain account information and balance
Data preparation for behavior scorecard modeling
B-end e-commerce - reverse order process
26 FPS video super-resolution model DAP! Output 720p Video Online
随机推荐
[fluent] dart function (function composition | private function | anonymous function | function summary)
Record the problems encountered by nodejs asynchronism
Activation function - relu vs sigmoid
Taiwan SSS Xinchuang sss1700 replaces cmmedia cm6533 24bit 96KHz USB audio codec chip
[cloud native topic -50]:kubesphere cloud Governance - operation - step by step deployment of microservice based business applications - database middleware MySQL microservice deployment process
Structured text language XML
Longest public prefix of leetcode
Implementing yolox from scratch: dataset class
Add two numbers of leetcode
1005 spell it right (20 points) "PTA class a exercise"
Volvo's first MPV is exposed! Comfortable and safe, equipped with 2.0T plug-in mixing system, it is worth first-class
Redis sentinel cluster working principle and architecture deployment # yyds dry goods inventory #
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
Highly qualified SQL writing: compare lines. Don't ask why. Asking is highly qualified..
Sword finger offer (I) -- handwriting singleton mode
Friends who firmly believe that human memory is stored in macromolecular substances, please take a look
6 pyspark Library
Use graalvm native image to quickly expose jar code as a native shared library
After eight years of test experience and interview with 28K company, hematemesis sorted out high-frequency interview questions and answers
[internship] solve the problem of too long request parameters