最近一门课程实验需要用到Go语言,久闻其名,为了减少以后配置的坑,特地记了一些笔记。不定期更新。

1. Go的下载与安装

在下载页选择合适的版本下载。这里我选择的是go1.15.6.linux-amd64.tar.gz稳定版。

sudo tar -C /usr/local -xzf go1.15.6.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin
$ go version
go version go1.15.6 linux/amd64

2. Go语言初探

用于用惯了IDEA与PyCharm,因此我也选择了Jetbrains家的Goland IDE。直接使用Jetbrains Toolbox可以方便下载。这是收费的,学生党可以用学校的邮箱去申请。没有licence的话可以使用免费的VSCode来开发。

2.1 Hello World

hellohello.go
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

在命令行输入如下命令即可运行。

go run hello.go

2.2 调用外部包的代码

quote
package main

import "fmt"

import "rsc.io/quote"

func main() {
    fmt.Println(quote.Go())
}
go.mod
$ go mod init hello
go: creating new go.mod: module hello
gorun
$ go: finding module for package rsc.io/quote
hello.go:4:8: 
module rsc.io/quote: Get "https://proxy.golang.org/rsc.io/quote/@v/list": dial tcp 172.217.24.17:443: i/o timeout

显然,在国内访问被墙了。考虑更换代理

go env -w GOPROXY=https://goproxy.cn

然后发现

$ go run hello.go 
go: finding module for package rsc.io/quote
go: writing stat cache: mkdir /usr/local/go/bin/pkg: permission denied
go: downloading rsc.io/quote v1.5.2
hello.go:4:8: mkdir /usr/local/go/bin/pkg: permission denied

没想到还有权限问题。

sudo chmod -R 777 /usr/local/go

这下终于成功了

$ go run hello.go
go: finding module for package rsc.io/quote
go: downloading rsc.io/quote v1.5.2
go: found rsc.io/quote in rsc.io/quote v1.5.2
go: downloading rsc.io/sampler v1.3.0
go: downloading golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c
Don't communicate by sharing memory, share memory by communicating.

3. 创建 Go 模块

greetings
$ go mod init example.com/greetings
go: creating new go.mod: module example.com/greetings
go.mod
module example.com/greetings

go 1.15
greetings.go
package greetings

import "fmt"

// Hello returns a greeting for the named person.
func Hello(name string) string {
    // Return a greeting that embeds the name in a message.
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message
}
:=
var message string
message = fmt.Sprintf("Hi, %v. Welcome!", name)

4.从另一个模块中调用模块

hello.go
package main

import (
    "fmt"

    "example.com/greetings"
)

func main() {
    // Get a greeting message and print it.
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}

并创建一个新模块

$ go mod init hello                
go: creating new go.mod: module hello

之后编辑hello模块来使用未发布的greetings模块

module hello

go 1.15

replace example.com/greetings => ../greetings
$ go build         
go: found example.com/greetings in example.com/greetings v0.0.0-00010101000000-000000000000
module hello

go 1.15

replace example.com/greetings => ../greetings

require example.com/greetings v0.0.0-00010101000000-000000000000
./hello       
Hi, Gladys. Welcome!

参考链接