安装Goland2022.2.5 版本
1.官网下载goland-2022.2.5.dmg版本(Mac)版本。如果是windows版本也可以直接下载)
2.配置gopath,基本都是配置.我这里配置为/usr/local/go 作为全目录,如果是windows,直接在环境中配置path路径就好。
3.查看版本 go version
go version
go version go1.19.3 darwin/amd64
建立工作目录gowork
基本目录结构为gowork/hello
gowork/greetings 2个目录文件
目录结构为:
建立hello.go文件
package main
import (
"fmt"
"example.com/greetings"
)
func main() {
// Get a greeting message and print it.
message := greetings.Hello("XiaMenKeny")
fmt.Println(message)
}
保存的时候,会提示错误。因为里面有调用example.com/greetings的引用包
建立greetings.go文件,在greetings目录下
package main
import (
"fmt"
"example.com/greetings"
)
func main() {
// Get a greeting message and print it.
message := greetings.Hello("XiaMenKeny")
fmt.Println(message)
}
分别建立2个文件。这个时候再进行会提示找不到
example.com/hello
module to use your local example.com/greetings
需要在原先环境下编辑一下mod,用命令,实际是修改到本地的目录文件上
go mod edit -replace example.com/greetings=../greetings
打开看go.mod 就可以看到已经变为,说明已经修改到本地目录上的
module example.com/hello
go 1.19
require (
example.com/greetings v0.0.0-00010101000000-000000000000
github.com/isdamir/gotype v0.0.0-20200101084212-6aa1591106b2
rsc.io/quote v1.5.2
)
require (
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c // indirect
rsc.io/sampler v1.3.0 // indirect
)
replace example.com/greetings => ../greetings
运行Hello 调用greetings里面的函数方法
go run hello.go
Hi, XiaMenKeny. Welcome by keny16999 from Beijing !
说明hello.go 已经调用了greetings.go里面的Hello方法。传输的参数是字符串
代码需要完善如果不知道谁调动的,需要返回一个错误
hello.go 修改带2参数的判断error
package main
import (
"fmt"
"log"
"example.com/greetings"
)
func main() {
// Get a greeting message and print it.
log.SetPrefix("greetings: ")
log.SetFlags(0)
// Request a greeting message.
message, err := greetings.Hello("")
// If an error was returned, print it to the console and
// exit the program.
if err != nil {
log.Fatal(err)
}
//greetings.Hello("XiaMenKeny")
fmt.Println(message)
}
G
我们可以直接运行这里直接传入一个空串,查看是否有错误出现,正确返回错误信息,
go run hello.go
greetings: empty name
exit status 1
空的名称确实不好,这样修改为随机返回一个字符串
package greetings
import (
"errors"
"fmt"
"math/rand"
"time"
)
// 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
}
// init sets initial values for variables used in the function.
func init() {
rand.Seed(time.Now().UnixNano())
}
// randomFormat returns one of a set of greeting messages. The returned
// message is selected at random.
func randomFormat() string {
// A slice of message formats.
formats := []string{
"Hi, %v. Welcome by keny16999 from Beijing !",
"Great to see you, %v!",
"Hail, %v! Well met!",
}
// Return a randomly selected message format by specifying
// a random index for the slice of formats.
return formats[rand.Intn(len(formats))]
}
修改hello.go
实践上代码是随机抽取字符串的3个字符串,代码比较简单,直接过就好。
#go run hello.go
Great to see you, Gladys!
#go run hello.go
Hi, kenyabc. Welcome by keny16999 from Beijing !
#go run hello.go
Hail, kenyabc! Well met!
继续修改,返回Map(key,value)值
继续修改greetings.go代码
package greetings
import (
"errors"
"fmt"
"math/rand"
"time"
)
// 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
}
// Hellos returns a map that associates each of the named people
// with a greeting message.
func Hellos(names []string) (map[string]string, error) {
// A map to associate names with messages.
messages := make(map[string]string)
// Loop through the received slice of names, calling
// the Hello function to get a message for each name.
for _, name := range names {
message, err := Hello(name)
if err != nil {
return nil, err
}
// In the map, associate the retrieved message with
// the name.
messages[name] = message
}
return messages, nil
}
// Init sets initial values for variables used in the function.
func init() {
rand.Seed(time.Now().UnixNano())
}
// randomFormat returns one of a set of greeting messages. The returned
// message is selected at random.
func randomFormat() string {
// A slice of message formats.
formats := []string{
"Hi, %v. Welcome!",
"Great to see you, %v!",
"Hail, %v! Well met!",
}
// Return one of the message formats selected at random.
return formats[rand.Intn(len(formats))]
}
修改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)
// A slice of names.
names := []string{"机器猫", "多爱猫", "天猫"}
// Request greeting messages for the names.
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)
}
运行结果
go run hello.go
map[多爱猫:Hail, 多爱猫! Well met! 天猫:Hail, 天猫! Well met! 机器猫:Hi, 机器猫. Welcome!]
返回name多个参数,里面有3个全部返回
建立一个测试代码greetings_test.go.
package greetings
import (
"testing"
"regexp"
)
// TestHelloName calls greetings.Hello with a name, checking
// for a valid return value.
func TestHelloName(t *testing.T) {
name := "Gladys"
want := regexp.MustCompile(`\b`+name+`\b`)
msg, err := Hello("Gladys")
if !want.MatchString(msg) || err != nil {
t.Fatalf(`Hello("Gladys") = %q, %v, want match for %#q, nil`, msg, err, want)
}
}
// TestHelloEmpty calls greetings.Hello with an empty string,
// checking for an error.
func TestHelloEmpty(t *testing.T) {
msg, err := Hello("")
if msg != "" || err == nil {
t.Fatalf(`Hello("") = %q, %v, want "", error`, msg, err)
}
}
测试直接用go test运行
下面说明没有发现测试文件。需要查看一下目录
go test
? example.com/hello [no test files]
测试文件建立在greetings目录下,要在greetings目录下运行
go test -v
=== RUN TestHelloName
--- PASS: TestHelloName (0.00s)
=== RUN TestHelloEmpty
--- PASS: TestHelloEmpty (0.00s)
PASS
ok example.com/greetings 0.016s
说明空的参数也通过。
时间上要修改一下greetings.go代码,区别就是参数传递的时候,有个是空的,目的是测试一个空的函数是否提示正确
// message := fmt.Sprintf(randomFormat(), name)
message := fmt.Sprint(randomFormat())
TestHelloName
greetings_test.go:15: Hello("Gladys") = "Hi, %v. Welcome!", <nil>, want match for `\bGladys\b`, nil
--- FAIL: TestHelloName (0.00s)
明显是说明需要参数传递的。
编译和安装代码
$ go build
Mac和linux编译为hello执行文件,如果不可以执行,手工修改一下属性,变成可以执行的
$ go build
./hello
map[Gladys:Hail, Gladys! Well met! 多爱猫:Hail, 多爱猫! Well met! 天猫:Hail, 天猫! Well met!]
把代码添加到你的gopath里面去,相当于部署到bin目录中 hello目录下输入go install 将hello新编译的文件已经注册到新的目录去。