当前位置:网站首页>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 .
边栏推荐
- Dora (discover offer request recognition) process of obtaining IP address
- 【MySQL 13】安装MySQL后第一次修改密码,可以可跳过MySQL密码验证进行登录
- Leetcode 198: house raiding
- Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function
- Reconnaissance et détection d'images - Notes
- Analysis of the problems of the 10th Blue Bridge Cup single chip microcomputer provincial competition
- Epoll related references
- PdfWriter. GetInstance throws system Nullreferenceexception [en] pdfwriter GetInstance throws System. NullRef
- The babbage industrial policy forum
- The underlying mechanism of advertising on websites
猜你喜欢
随机推荐
Read config configuration file of vertx
An overview of IfM Engage
Image recognition and detection -- Notes
Technical dry goods Shengsi mindspire operator parallel + heterogeneous parallel, enabling 32 card training 242 billion parameter model
Mail sending of vertx
IO stream system and FileReader, filewriter
《指環王:力量之戒》新劇照 力量之戒鑄造者亮相
技术干货|百行代码写BERT,昇思MindSpore能力大赏
Circuit, packet and message exchange
Vertx's responsive MySQL template
Inverted chain disk storage in Lucene (pfordelta)
Technical dry goods | alphafold/ rosettafold open source reproduction (2) - alphafold process analysis and training Construction
Longest common prefix and
The difference between typescript let and VaR
Common operations of JSP
Vertx metric Prometheus monitoring indicators
技术干货|昇思MindSpore初级课程上线:从基本概念到实操,1小时上手!
Jeecg data button permission settings
【开发笔记】基于机智云4G转接板GC211的设备上云APP控制
技术干货|关于AI Architecture未来的一些思考