• Go for Return Day1 20230919


    Return and handle an error

    In greetings/greetings.go, add the code below.

    1. package greetings
    2. import (
    3. "errors"
    4. "fmt"
    5. )
    6. // Hello returns a greeting for the named person.
    7. func Hello(name string) (string, error) {
    8. // If no name was given, return an error with a message.
    9. if name == "" {
    10. return "", errors.New("empty name")
    11. }
    12. // If a name was received, return a value that embeds the name
    13. // in a greeting message.
    14. message := fmt.Sprintf("Hi, %v. Welcome!", name)
    15. return message, nil
    16. }

    2.In your hello/hello.go file, handle the error now returned by the Hello function, along with the non-error value.

    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. // Request a greeting message
    14. message, err := greetings.Hello("")
    15. // If an error was returned , print it to the console and exit the program.
    16. if err != nil {
    17. log.Fatal(err)
    18. }
    19. // If no error was returned , print the returned message to the console.
    20. fmt.Println(message)
    21. }

    3.At the command line in the hello directory, run hello.go to confirm that the code works.

    Return a random greeting

    • Add a randomFormat function that returns a randomly selected format for a greeting message. Note that randomFormat starts with a lowercase letter, making it accessible only to code in its own package (in other words, it's not exported).
    • In randomFormat, declare a formats slice with three message formats. When declaring a slice, you omit its size in the brackets, like this: []string. This tells Go that the size of the array underlying the slice can be dynamically changed.
    • Use the math/rand package to generate a random number for selecting an item from the slice.
    • In Hello, call the randomFormat function to get a format for the message you'll return, then use the format and name value together to create the message.
    • Return the message (or an error) as you did before.
    1. package greetings
    2. import (
    3. "errors"
    4. "fmt"
    5. "math/rand"
    6. )
    7. // Hello returns a greeting for the named person.
    8. func Hello(name string) (string, error) {
    9. // If no name was given, return an error with a message.
    10. if name == "" {
    11. return name, errors.New("empty name")
    12. }
    13. // Create a message using a random format.
    14. message := fmt.Sprintf(randomFormat(), name)
    15. return message, nil
    16. }
    17. // randomFormat returns one of a set of greeting messages. The returned
    18. // message is selected at random.
    19. func randomFormat() string {
    20. // A slice of message formats.
    21. formats := []string{
    22. "Hi, %v. Welcome!",
    23. "Great to see you, %v!",
    24. "Hail, %v! Well met!",
    25. }
    26. // Return a randomly selected message format by specifying
    27. // a random index for the slice of formats.
    28. return formats[rand.Intn(len(formats))]
    29. }
    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. // Request a greeting message.
    14. message, err := greetings.Hello("Maxwell")
    15. // If an error was returned, print it to the console and
    16. // exit the program.
    17. if err != nil {
    18. log.Fatal(err)
    19. }
    20. // If no error was returned, print the returned message
    21. // to the console.
    22. fmt.Println(message)
    23. }

    At the command line, in the hello directory, run hello.go to confirm that the code works. Run it multiple times, noticing that the greeting changes.

    Return greetings for multiple people

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

  • 相关阅读:
    ZULL图解+代码 ZuulFilter执行顺序
    Javascript的同步与异步,异步的宏任务与微任务——事件循环
    MySQL —— 索引
    backurl: heytapbrowser://main/iflow?sub_target=only_enter_iflow
    map和set详解
    为什么 AI 时代更应该 Learn in Public
    DDD领域驱动设计-视频讲解+实战
    【WINDOWS / DOS 批处理】IF命令之比较运算符证明实例
    Spring Boot 3.0.0 M3、2.7.0发布,2.5.x将停止维护
    基于SpringBoot+Mybatis+layui的学生成绩管理系统
  • 原文地址:https://blog.csdn.net/u011868279/article/details/133024263