当前位置:网站首页>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 .
边栏推荐
- 技术干货|昇思MindSpore创新模型EPP-MVSNet-高精高效的三维重建
- UA camouflage, get and post in requests carry parameters to obtain JSON format content
- Responsive MySQL of vertx
- 你开发数据API最快多长时间?我1分钟就足够了
- Pgadmin 4 v6.11 release, PostgreSQL open source graphical management tool
- Project experience sharing: Based on mindspore, the acoustic model is realized by using dfcnn and CTC loss function
- Topic | synchronous asynchronous
- 項目經驗分享:實現一個昇思MindSpore 圖層 IR 融合優化 pass
- 技术干货|昇思MindSpore Lite1.5 特性发布,带来全新端侧AI体验
- Leetcode 213: looting II
猜你喜欢
Collector in ES (percentile / base)
TreeMap
Technical dry goods | reproduce iccv2021 best paper swing transformer with Shengsi mindspire
Analysis of the problems of the 12th Blue Bridge Cup single chip microcomputer provincial competition
[mindspire paper presentation] summary of training skills in AAAI long tail problem
技术干货|AI框架动静态图统一的思考
【LeetCode】4. Best Time to Buy and Sell Stock·股票买卖最佳时机
How long is the fastest time you can develop data API? One minute is enough for me
Introduction of buffer flow
Various postures of CS without online line
随机推荐
Rabbit MQ message sending of vertx
[set theory] Stirling subset number (Stirling subset number concept | ball model | Stirling subset number recurrence formula | binary relationship refinement relationship of division)
论文学习——鄱阳湖星子站水位时间序列相似度研究
Partage de l'expérience du projet: mise en œuvre d'un pass optimisé pour la fusion IR de la couche mindstore
GStreamer ffmpeg avdec decoded data flow analysis
【MindSpore论文精讲】AAAI长尾问题中训练技巧的总结
Technical dry goods Shengsi mindspire innovation model EPP mvsnet high-precision and efficient 3D reconstruction
VMware virtual machine installation
The difference between typescript let and VaR
专题 | 同步 异步
Talk about floating
Comparison of advantages and disadvantages between most complete SQL and NoSQL
技术干货|昇思MindSpore可变序列长度的动态Transformer已发布!
图像识别与检测--笔记
技术干货|昇思MindSpore NLP模型迁移之Roberta ——情感分析任务
Paper learning -- Study on the similarity of water level time series of Xingzi station in Poyang Lake
IndexSort
Analysis of the problems of the 11th Blue Bridge Cup single chip microcomputer provincial competition
技术干货|昇思MindSpore算子并行+异构并行,使能32卡训练2420亿参数模型
Industrial resilience