作为Google最开始内部使用的语言,随着国内头部企业的一些项目都使用Go语言,还是有必要去学习它,跟Python的比较就不多说了,因为语言这东西都是有优缺点的,在本人的眼里就是看需求,适合什么语言就使用什么语言。
安装(根据自己的系统环境来选择):Download and install - The Go Programming Language
初步学习的话,其实官网都是有提供的:https://golang.google.cn/doc/tutorial/
这里是针对一些英文薄弱,想快速熟悉这门语言的伙伴们而写的入门文章,安装好了之后,我们打开命令提示符,输入go,就有帮助提示,如图:
比如查看go的版本
C:\Users\Tony>go version
go version go1.19.2 windows/amd64
代码开工
我们来创建一个test.go文件,输入代码如下:
package main
import "fmt"
func main() {
fmt.Print("零基础学习Go语言")
}
C:\Users\Tony>go run test.go
零基础学习Go语言
我们可以看到,只要有点语言基础的,还是可以很容易看懂。
定义包名,然后加载模块,fmt(format格式化)这个包,有输出到控制台的函数,Python是四个空格的写法,这里的Go还是沿袭大部分的大括号写法。
定义函数使用func,而Python是def,注意一些语法格式的区别即可
生成可执行的文件(二进制文件)test.exe
C:\Users\Tony>go build test.go
C:\Users\Tony>test
零基础学习Go语言
创建模块与调用(依赖项)
两个模块:greetings目录与hello目录,在hello目录下的hello.go调用greetings目录下的greetings.go函数
创建greetings目录与自定义一个模块,名称:example.com/greetings
C:\Users\Tony>mkdir greetings
C:\Users\Tony>cd greetings
C:\Users\Tony\greetings>go mod init example.com/greetings
go: creating new go.mod: module example.com/greetings
greetings.go
注意函数参数声明的写法与返回值的声明
package greetings
import "fmt"
func Hello(n string) string {
message := fmt.Sprintf("Hi, %v. You're a good man!", n)
return message
}
创建hello目录与自定义一个模块,名称:example.com/hello
C:\Users\Tony\greetings>cd ..
C:\Users\Tony>mkdir hello
C:\Users\Tony>cd hello
C:\Users\Tony\hello>go mod init example.com/hello
go: creating new go.mod: module example.com/hello
hello.go
加载多个模块,使用小括号括起来
package main
import (
"fmt"
"example.com/greetings"
)
func main() {
message := greetings.Hello("Tony")
fmt.Println(message)
}
我们来运行hello.go这个go语言的源文件
C:\Users\Tony\hello>go run hello.go
将发生错误,没有提供这个example.com/greetings包:
hello.go:6:5: no required module provides package example.com/greetings; to add it:
go get example.com/greetings
为了找到这个包,还需要以下几个操作:
C:\Users\Tony\hello>go mod edit -replace example.com/greetings=../greetings
这样会在hello目录下面的go.mod,多出一行:replace example.com/greetings => ../greetings,意思就是可以使用example.com/greetings来代替../greetings,这样就可以定位到这个依赖,然后做依赖添加操作:
C:\Users\Tony\hello>go mod tidy
将需要的依赖项添加到go.mod,同时也会将不需要的剔除掉,这个时候我们可以看到在go.mod里面,增加了这行:
require example.com/greetings v0.0.0-00010101000000-000000000000
这样就可以正确的调用模块了,从模块调用这块来看是要比Python繁琐。
C:\Users\Tony\hello>go run hello.go
Hi, Tony. You're a good man!