当前位置:网站首页>Go language foundation ----- 01 ----- go language features
Go language foundation ----- 01 ----- go language features
2022-07-03 07:36:00 【Mango sauce】
One go Linguistic characteristics
1.1 Development environment construction
It's actually installation go Environment and GoLand IDE Tools .
go Language environment :go Locale download address .
You need to pay attention to this download : First, use the following command to view the corresponding win System architecture , Select the corresponding version , Otherwise, in the vscode When downloading plug-ins ,dlv And dlv-map Will not be able to download .
echo %PROCESSOR_ARCHITECTURE%
# perhaps echo %PROCESSOR_IDENTIFIER% 、systeminfo. Here I use the first direct view is AMD64 framework
So in choosing windows Software package for , You have to choose to have amd Situation of words , And choose msi Suffix , This means that you can directly install , No other steps are needed .
GoLand IDE Tools :GoLand IDE Tool download address . However, this version that you want to crack needs a compressed package .
stay debug front , It's best to execute the following command first , Prevent the influence mod Project .
go env -w GO111MODULE=off
stay vscode Conduct debug, After installing all plug-ins , I want to debug, however vscode Has been an error , Error is as follows :
unable to locate "go" binary in GOROOT () or PATH(xxx)
It probably means that there is no corresponding go.exe Binary , But I'm directly in cmd above go env It works , And I clearly see the system of environment variables Path notice GOROOT The path of . I thought it was GOPATH Under the src Cannot exist alone xxx.go file , But when I'm done , It's no problem to put it alone . So the question should be : Or vscoe The problem of , Or go Own path problem .
I solved it like this : New on desktop go_src Catalog , Create a subdirectory inside src.src add to test.go file , And then " desktop \go_src" Add path to GOPATH In the environment variables . Use vscode again debug, Then you can succeed debug 了 .
Then continue to want to repeat the above problem , But the same directory architecture and debug The way , It works , So this mistake is either a guess or vscoe The problem of , Or go Own path problem .
go stay vscode Of debug Than C++ Simple , Click Run , Then it will fail , Because you didn't create it for the first time launch.json file , Directly click to create without changing the content debug 了 .
1.2.1 Go Linguistic characteristics - Garbage collection
- a. Automatic memory recycling , No more developers managing memory .
- b. Developers focus on business implementation , It reduces the mental burden .
- c. It only needs new Allocate memory , No need to release .
- d. gc Garbage collection 4ms.
1.2.2 Go Linguistic characteristics - Natural concurrence
- a. Support concurrency from the language level , It's simple .
- b. goroute, Lightweight threads , Create thousands of goroute Make it possible .
- c. be based on CSP(Communicating Sequential Process) Model implementation .
Test code :
// goroute.go
// 1. A file belongs to a package , This indicates that this file belongs to main This package , A package can have multiple files .
package main
// 2. Import other libraries . If the package is not used ,go Will report a mistake , Strict grammar .
import (
"fmt"
)
// 3. The functions of the package
func test_goroute(a int) {
fmt.Println(a)
}
// main.go
// 4. Note the need for main The directory execution of the upper layer of the function is E:\go_study\go_code\1-src\src\1:go run .\1-1-goroute\
// Otherwise it will fail
package main
import (
"time"
)
func main() {
// 5. Start a hundred collaborative processes .go The keyword represents the starting process .
// go The process of cooperation in is : Open up in a thread , When opening up multiple collaborative processes , They do not interfere with each other , All are executed asynchronously . So printing can see that the order is disordered .
for i := 0; i < 100; i++ {
go test_goroute(i)
}
// sleep 1 second
time.Sleep(time.Second)
}
1.2.3 Go Linguistic characteristics -channel
- a. The Conduit , similar unix/linux Medium pipe, fifo , One end is reading, and the other end is writing ,channel It's process safe , There will be a lock inside . And previous C Language synergy comparison , A thread can run multiple coprocedures , But there is no race relationship ,1:n The relationship between , It is safe for multiple coroutines to access global variables , It can be considered that one thread polls multiple threads . and go Between threads and coroutines of m:n Relationship , There is a race relationship .
- b. Multiple goroute Through between channel communicate .
- c. Support any type .
Code testing :
package main
import "fmt"
func test_pipe() {
pipe := make(chan int, 3)
pipe <- 1
pipe <- 2
pipe <- 3
var t1 int
t1 = <-pipe
fmt.Println("t1: ", t1)
}
func sum(s []int, c chan int) {
//test_pipe()
sum := 0
for _, v := range s {
sum += v
}
fmt.Println("sum:", sum)
c <- sum // send sum to c
}
func main() {
// 1. Defining slices s
s := []int{
7, 2, 8, -9, 4, 0}
// 2. Create channels c
c := make(chan int)
// 3. Pass the first half of the slice elements and channels into the coroutine , Cumulative sum of processes , then push To the passage .
go sum(s[:len(s)/2], c) // 7+2+8 = 17, -9 + 4+0 = -5
// 4. Empathy , Transfer the elements and channels of the second half of the slice into the coroutine , Cumulative sum of processes , then push To the passage .
go sum(s[len(s)/2:], c)
// 5. At this time, the channel should have two statistical values . Let's get , Follow the first in, first out rule of the channel .
// x, y := <-c, <-c // receive from c
x := <-c
y := <-c
fmt.Println(x, y, x+y)
}
result :
1.2.4 Go Linguistic characteristics - Multiple return values
go A function of returns multiple values , similar lua.
Test code :
My directory structure is like this , Use up to four go file .add.go、calc.go、sub.go、main.go.
// add.go
package calc
func Add(a int, b int) int {
return a + b
}
// calc.go
package calc
func Calc(a int, b int)(int,int) {
sum := a + b
avg := (a+b)/2
return sum, avg
}
// sub.go
package calc
func Sub(a int, b int) int {
return a - b
}
// main.go
package main
// Because I'm here GOPATH Set up E:\go_study\go_code\1-src For environment variables , and go It will automatically find src Catalog ,
// So below import calc Packet time , Its path is :"1/1-3-package/calc".
// But note that sometimes after adding environment variables , It doesn't take effect immediately , You may need to wait .
import (
"1/1-3-package/calc"
"fmt"
)
func main() {
sum := calc.Add(100, 300)
sub := calc.Sub(100, 300)
fmt.Println("sum=", sum)
fmt.Println("sub=", sub)
sum, avg := calc.Calc(100, 300)
fmt.Println("sum=", sum)
fmt.Println("avg=", avg)
}
result :
1.3 first golang Program
It's printing hello woeld, It's not shown here .
1.4.1 The concept of a package
- and python equally , Put the code of the same function into a directory , Call it a bag .
- Packages can be referenced by other packages .
- main Packages are used to generate executable files , There is only one per program main package .
- The main purpose of the package is to improve the reusability of the code .
1.4.2 The actual combat of Bao
That is, how to reference your own package , Look back to the above 1.2.4 Go Linguistic characteristics - Examples of multiple return values are sufficient .
Two summary
- 1) This section is mainly about go How to install the environment and related syntax , How to compile and run , And related concepts .
边栏推荐
- Jeecg data button permission settings
- Circuit, packet and message exchange
- Leetcode 213: looting II
- 最全SQL与NoSQL优缺点对比
- IO stream system and FileReader, filewriter
- Vertx's responsive redis client
- Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function
- Warehouse database fields_ Summary of SQL problems in kingbase8 migration of Jincang database
- Leetcode 213: 打家劫舍 II
- Use of other streams
猜你喜欢
Homology policy / cross domain and cross domain solutions /web security attacks CSRF and XSS
项目经验分享:基于昇思MindSpore实现手写汉字识别
PAT甲级 1032 Sharing
技术干货|昇思MindSpore NLP模型迁移之Roberta ——情感分析任务
Technical dry goods Shengsi mindspire lite1.5 feature release, bringing a new end-to-end AI experience
Margin left: -100% understanding in the Grail layout
Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function
Understanding of class
Leetcode 198: house raiding
[mindspire paper presentation] summary of training skills in AAAI long tail problem
随机推荐
Common methods of file class
Grpc message sending of vertx
技术干货|昇思MindSpore初级课程上线:从基本概念到实操,1小时上手!
技术干货|昇思MindSpore可变序列长度的动态Transformer已发布!
Robots protocol
论文学习——鄱阳湖星子站水位时间序列相似度研究
Traversal in Lucene
昇思MindSpore再升级,深度科学计算的极致创新
PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef
UA camouflage, get and post in requests carry parameters to obtain JSON format content
Analysis of the ninth Blue Bridge Cup single chip microcomputer provincial competition
Jeecg menu path display problem
What did the DFS phase do
Download address collection of various versions of devaexpress
The concept of C language pointer
HISAT2 - StringTie - DESeq2 pipeline 进行bulk RNA-seq
【LeetCode】2. Valid Parentheses·有效的括号
Lucene merge document order
C code production YUV420 planar format file
Use of generics