• GoLand2022.2.5版本Hello调动Greetings包


    安装Goland2022.2.5 版本

    1.官网下载goland-2022.2.5.dmg版本(Mac)版本。如果是windows版本也可以直接下载)

    2.配置gopath,基本都是配置.我这里配置为/usr/local/go 作为全目录,如果是windows,直接在环境中配置path路径就好。

    3.查看版本 go version 

    1. go version
    2. go version go1.19.3 darwin/amd64

    建立工作目录gowork

    基本目录结构为gowork/hello

                             gowork/greetings 2个目录文件

    目录结构为:

     

    建立hello.go文件

    1. package main
    2. import (
    3. "fmt"
    4. "example.com/greetings"
    5. )
    6. func main() {
    7. // Get a greeting message and print it.
    8. message := greetings.Hello("XiaMenKeny")
    9. fmt.Println(message)
    10. }

    保存的时候,会提示错误。因为里面有调用example.com/greetings的引用包

    建立greetings.go文件,在greetings目录下

    1. package main
    2. import (
    3. "fmt"
    4. "example.com/greetings"
    5. )
    6. func main() {
    7. // Get a greeting message and print it.
    8. message := greetings.Hello("XiaMenKeny")
    9. fmt.Println(message)
    10. }

    分别建立2个文件。这个时候再进行会提示找不到 

    example.com/hello module to use your local example.com/greetings

    需要在原先环境下编辑一下mod,用命令,实际是修改到本地的目录文件上

    go mod edit -replace example.com/greetings=../greetings

    打开看go.mod 就可以看到已经变为,说明已经修改到本地目录上的

    1. module example.com/hello
    2. go 1.19
    3. require (
    4. example.com/greetings v0.0.0-00010101000000-000000000000
    5. github.com/isdamir/gotype v0.0.0-20200101084212-6aa1591106b2
    6. rsc.io/quote v1.5.2
    7. )
    8. require (
    9. golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c // indirect
    10. rsc.io/sampler v1.3.0 // indirect
    11. )
    12. replace example.com/greetings => ../greetings

    运行Hello 调用greetings里面的函数方法

    1. go run hello.go
    2. Hi, XiaMenKeny. Welcome by keny16999 from Beijing !

    说明hello.go 已经调用了greetings.go里面的Hello方法。传输的参数是字符串

    代码需要完善如果不知道谁调动的,需要返回一个错误

    hello.go 修改带2参数的判断error

    1. package main
    2. import (
    3. "fmt"
    4. "log"
    5. "example.com/greetings"
    6. )
    7. func main() {
    8. // Get a greeting message and print it.
    9. log.SetPrefix("greetings: ")
    10. log.SetFlags(0)
    11. // Request a greeting message.
    12. message, err := greetings.Hello("")
    13. // If an error was returned, print it to the console and
    14. // exit the program.
    15. if err != nil {
    16. log.Fatal(err)
    17. }
    18. //greetings.Hello("XiaMenKeny")
    19. fmt.Println(message)
    20. }
    21. G

    我们可以直接运行这里直接传入一个空串,查看是否有错误出现,正确返回错误信息,

    1. go run hello.go
    2. greetings: empty name
    3. exit status 1

    空的名称确实不好,这样修改为随机返回一个字符串

    1. package greetings
    2. import (
    3. "errors"
    4. "fmt"
    5. "math/rand"
    6. "time"
    7. )
    8. // Hello returns a greeting for the named person.
    9. func Hello(name string) (string, error) {
    10. // If no name was given, return an error with a message.
    11. if name == "" {
    12. return name, errors.New("empty name")
    13. }
    14. // Create a message using a random format.
    15. message := fmt.Sprintf(randomFormat(), name)
    16. return message, nil
    17. }
    18. // init sets initial values for variables used in the function.
    19. func init() {
    20. rand.Seed(time.Now().UnixNano())
    21. }
    22. // randomFormat returns one of a set of greeting messages. The returned
    23. // message is selected at random.
    24. func randomFormat() string {
    25. // A slice of message formats.
    26. formats := []string{
    27. "Hi, %v. Welcome by keny16999 from Beijing !",
    28. "Great to see you, %v!",
    29. "Hail, %v! Well met!",
    30. }
    31. // Return a randomly selected message format by specifying
    32. // a random index for the slice of formats.
    33. return formats[rand.Intn(len(formats))]
    34. }

    修改hello.go

    实践上代码是随机抽取字符串的3个字符串,代码比较简单,直接过就好。

    1. #go run hello.go
    2. Great to see you, Gladys!
    3. #go run hello.go
    4. Hi, kenyabc. Welcome by keny16999 from Beijing !
    5. #go run hello.go
    6. Hail, kenyabc! Well met!

    继续修改,返回Map(key,value)值

    继续修改greetings.go代码

    1. package greetings
    2. import (
    3. "errors"
    4. "fmt"
    5. "math/rand"
    6. "time"
    7. )
    8. // Hello returns a greeting for the named person.
    9. func Hello(name string) (string, error) {
    10. // If no name was given, return an error with a message.
    11. if name == "" {
    12. return name, errors.New("empty name")
    13. }
    14. // Create a message using a random format.
    15. message := fmt.Sprintf(randomFormat(), name)
    16. return message, nil
    17. }
    18. // Hellos returns a map that associates each of the named people
    19. // with a greeting message.
    20. func Hellos(names []string) (map[string]string, error) {
    21. // A map to associate names with messages.
    22. messages := make(map[string]string)
    23. // Loop through the received slice of names, calling
    24. // the Hello function to get a message for each name.
    25. for _, name := range names {
    26. message, err := Hello(name)
    27. if err != nil {
    28. return nil, err
    29. }
    30. // In the map, associate the retrieved message with
    31. // the name.
    32. messages[name] = message
    33. }
    34. return messages, nil
    35. }
    36. // Init sets initial values for variables used in the function.
    37. func init() {
    38. rand.Seed(time.Now().UnixNano())
    39. }
    40. // randomFormat returns one of a set of greeting messages. The returned
    41. // message is selected at random.
    42. func randomFormat() string {
    43. // A slice of message formats.
    44. formats := []string{
    45. "Hi, %v. Welcome!",
    46. "Great to see you, %v!",
    47. "Hail, %v! Well met!",
    48. }
    49. // Return one of the message formats selected at random.
    50. return formats[rand.Intn(len(formats))]
    51. }

    修改hello.go代码

    1. package main
    2. import (
    3. "fmt"
    4. "log"
    5. "example.com/greetings"
    6. )
    7. func main() {
    8. // Set properties of the predefined Logger, including
    9. // the log entry prefix and a flag to disable printing
    10. // the time, source file, and line number.
    11. log.SetPrefix("greetings: ")
    12. log.SetFlags(0)
    13. // A slice of names.
    14. names := []string{"机器猫", "多爱猫", "天猫"}
    15. // Request greeting messages for the names.
    16. messages, err := greetings.Hellos(names)
    17. if err != nil {
    18. log.Fatal(err)
    19. }
    20. // If no error was returned, print the returned map of
    21. // messages to the console.
    22. fmt.Println(messages)
    23. }

    运行结果

    go run hello.go
    map[多爱猫:Hail, 多爱猫! Well met! 天猫:Hail, 天猫! Well met! 机器猫:Hi, 机器猫. Welcome!]
    返回name多个参数,里面有3个全部返回

    建立一个测试代码greetings_test.go.

    1. package greetings
    2. import (
    3. "testing"
    4. "regexp"
    5. )
    6. // TestHelloName calls greetings.Hello with a name, checking
    7. // for a valid return value.
    8. func TestHelloName(t *testing.T) {
    9. name := "Gladys"
    10. want := regexp.MustCompile(`\b`+name+`\b`)
    11. msg, err := Hello("Gladys")
    12. if !want.MatchString(msg) || err != nil {
    13. t.Fatalf(`Hello("Gladys") = %q, %v, want match for %#q, nil`, msg, err, want)
    14. }
    15. }
    16. // TestHelloEmpty calls greetings.Hello with an empty string,
    17. // checking for an error.
    18. func TestHelloEmpty(t *testing.T) {
    19. msg, err := Hello("")
    20. if msg != "" || err == nil {
    21. t.Fatalf(`Hello("") = %q, %v, want "", error`, msg, err)
    22. }
    23. }

    测试直接用go test运行

    下面说明没有发现测试文件。需要查看一下目录

    1. go test
    2. ? example.com/hello [no test files]

    测试文件建立在greetings目录下,要在greetings目录下运行

    1. go test -v
    2. === RUN TestHelloName
    3. --- PASS: TestHelloName (0.00s)
    4. === RUN TestHelloEmpty
    5. --- PASS: TestHelloEmpty (0.00s)
    6. PASS
    7. ok example.com/greetings 0.016s

    说明空的参数也通过。

    时间上要修改一下greetings.go代码,区别就是参数传递的时候,有个是空的,目的是测试一个空的函数是否提示正确

    1. // message := fmt.Sprintf(randomFormat(), name)
    2. message := fmt.Sprint(randomFormat())
    1. TestHelloName
    2. greetings_test.go:15: Hello("Gladys") = "Hi, %v. Welcome!", <nil>, want match for `\bGladys\b`, nil
    3. --- FAIL: TestHelloName (0.00s)


    明显是说明需要参数传递的。

    编译和安装代码

    $ go build

    Mac和linux编译为hello执行文件,如果不可以执行,手工修改一下属性,变成可以执行的

    1. $ go build
    2. ./hello
    3. map[Gladys:Hail, Gladys! Well met! 多爱猫:Hail, 多爱猫! Well met! 天猫:Hail, 天猫! Well met!]

    把代码添加到你的gopath里面去,相当于部署到bin目录中 hello目录下输入go install 将hello新编译的文件已经注册到新的目录去。

  • 相关阅读:
    【Java实战】泄露用户隐私被罚巨款?系统被攻击?如何避免?
    流量1---------1
    MySQL 分组后统计 TopN 优化思路
    在k8s1.25版本中为何出现这种情况
    go语言中的读写操作以及文件的复制
    sqlmap语法介绍
    sv验证环境-分层验证平台
    【数据库】达梦数据库DM8开发版安装
    【element-ui】 el-form之rules赋值后校验没消失
    freeCodeCamp响应式网页设计笔记
  • 原文地址:https://blog.csdn.net/keny88888/article/details/128105172