# 这里example.com/greetings是命名模块的基本范式,<prefix>/<descriptive-text> eg:github.com/<project-name>
go mod init example.com/greetings
//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
}
hello 下初始化项目
go mod init example.com/hello
//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)
}
# 在 hello 目录中的命令提示符下,运行以下命令
go mod edit -replace example.com/greetings=../greetings
# 现在你再去看看hello\go.mod,然后同步模块的依赖项,再去观察
go mod tidy # 该命令在 greetings 目录中找到了本地代码,然后 添加了 require 指令以指定导入包时的依赖关系
go run .
输出样例
PS D:\projectCode\go\hello\hello> go mod edit -replace example.com/greetings=../greetings
PS D:\projectCode\go\hello\hello> go mod tidy
go: found example.com/greetings in example.com/greetings v0.0.0-00010101000000-000000000000
PS D:\projectCode\go\hello\hello> go run .
Hi, Gladys. Welcome!
好了,我想你已经掌握了一些小技巧,让我们继续,做一些异常处理
异常处理
修改greetings\greetings.go
// greetings.go
package greetings
import (
"errors" //导入 Go 标准库包,以便您可以 使用其错误。新功能。errors
"fmt"
)
// Hello returns a greeting for the named person.
func Hello(name string) (string, error) {
if name == "" { //添加语句以检查无效请求( 名称应为空字符串),并在 请求无效。该函数返回一个包含您的消息的函数。iferrors.Newerror
return "", errors.New("empty name") //更改函数,使其返回两个值:a 和 .检查 第二个值用于查看是否发生错误。(任何 Go 函数都可以 返回多个值。有
}
message := fmt.Sprintf("Hi, %v. Welcome!", name)
return message, nil // 添加(表示没有错误)作为 成功返回。这样,调用方可以看到函数 成功。nil
}
PS D:\projectCode\go\hello\hello> go run .
greetings: empty name
exit status 1
返回随机问候语
修改greetings\greetings.go
// greetings.go
package greetings
import (
"errors"
"fmt"
"math/rand"
)
// Hello returns a greeting for the named person.
func Hello(name string) (string, error) {
// If no name was given, return an error with a message.
if name == "" {
return name, errors.New("empty name")
}
// Create a message using a random format.
message := fmt.Sprintf(randomFormat(), name)
return message, nil
}
func randomFormat() string { //添加一个函数,该函数随机返回 选定的问候语格式。
// 声明一个切片 三种消息格式
formats := []string{
"Hi, %v. Welcome!",
"Great to see you, %v!",
"Hail, %v! Well met!",
}
使用 math/rand 包生成一个随机数,用于从切片中选择项目
return formats[rand.Intn(len(formats))]
}
PS D:\projectCode\go\hello\hello> go run .
Hi, Gladys. Welcome!
PS D:\projectCode\go\hello\hello> go run .
Hail, Gladys! Well met!
PS D:\projectCode\go\hello\hello> go run .
Great to see you, Gladys!
在一个请求中获取多个人的问候语
修改greetings\greetings.go
package greetings
import (
"errors"
"fmt"
"math/rand"
)
// returns a greeting for the named person.
func Hello(name string) (string, error) {
// If no name was given, return an error with a message.
if name == "" {
return name, errors.New("empty name")
}
// Create a message using a random format.
message := fmt.Sprintf(randomFormat(), name)
return message, nil
}
//新添加的函数 添加一个参数为名称切片的函数
func Hellos(names []string) (map[string]string, error) {
messages := make(map[string]string)
for _, name := range names {
message, err := Hello(name)
if err != nil {
return nil, err
}
messages[name] = message
}
return messages, nil
}
func randomFormat() string {
formats := []string{
"Hi, %v. Welcome!",
"Great to see you, %v!",
"Hail, %v! Well met!",
}
return formats[rand.Intn(len(formats))]
}
修改 hello\hello.go
package main
import (
"fmt"
"log"
"example.com/greetings"
)
func main() {
// Set properties of the predefined Logger, including
// the log entry prefix and a flag to disable printing
// the time, source file, and line number.
log.SetPrefix("greetings: ")
log.SetFlags(0)
// 创建一个变量作为包含三个的切片类型 名字。names
names := []string{"Gladys", "Samantha", "Darrin"}
// 将变量作为参数传递给函数。namesHellos
messages, err := greetings.Hellos(names)
if err != nil {
log.Fatal(err)
}
// If no error was returned, print the returned map of
// messages to the console.
fmt.Println(messages)
}
其实就是用循环输出了好多人的问候语
输出样例
PS D:\projectCode\book\go-tutorial\code\hello\hello> go run .
map[Darrin:Great to see you, Darrin! Gladys:Hail, Gladys! Well met! Samantha:Great to see you, Samantha!]
测试
以 _test.go 结尾的文件名会告诉命令 此文件包含测试函数。使用 go test可以进行测试。
PS D:\projectCode\book\go-tutorial\code\hello\greetings> go test
PASS
ok example.com/greetings 0.126s
PS D:\projectCode\book\go-tutorial\code\hello\greetings> go test -v
=== RUN TestHelloName
--- PASS: TestHelloName (0.00s)
=== RUN TestHelloEmpty
--- PASS: TestHelloEmpty (0.00s)
PASS
ok example.com/greetings 0.052s
故意编写错误函数
// 在 greetings/greetings.go 中,粘贴以下代码来代替 Hello 函数。
func Hello(name string) (string, error) {
// If no name was given, return an error with a message.
if name == "" {
return name, errors.New("empty name")
}
// Create a message using a random format.
// message := fmt.Sprintf(randomFormat(), name)
message := fmt.Sprint(randomFormat())
return message, nil
}
测试应不通过:
PS D:\projectCode\book\go-tutorial\code\hello\greetings> go test
--- FAIL: TestHelloName (0.00s)
greetings_test.go:16: Hello("Gladys") = "Great to see you, %v!", <nil>, want match for `\bGladys\b`, nil
FAIL
exit status 1
FAIL example.com/greetings 0.037s
PS D:\projectCode\book\go-tutorial\code\hello\greetings> go test -v
=== RUN TestHelloName
greetings_test.go:16: Hello("Gladys") = "Hail, %v! Well met!", <nil>, want match for `\bGladys\b`, nil
--- FAIL: TestHelloName (0.00s)
=== RUN TestHelloEmpty
--- PASS: TestHelloEmpty (0.00s)
FAIL
exit status 1
FAIL example.com/greetings 0.054s
编译应用程序
PS D:\projectCode\book\go-tutorial\code\hello> cd .\hello\
# 编译
PS D:\projectCode\book\go-tutorial\code\hello\hello> go build
# 执行编译文件
PS D:\projectCode\book\go-tutorial\code\hello\hello> .\hello.exe
map[Darrin:Hi, %v. Welcome! Gladys:Great to see you, %v! Samantha:Hail, %v! Well met!]
# 发现安装路径
PS D:\projectCode\book\go-tutorial\code\hello\hello> go list -f '{{.Target}}'
C:\Users\lushi\go\bin\hello.exe # 可以把C:\Users\lushi\go\bin\放环境中,完成安装