Learning Go Programming Language

Notes

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
}
  • In Go, a function whose name starts with a capital letter can be called by a function not in the same package. This is known in Go as an exported name.
function-syntax.png (589×164)
  • In Go, the := operator is a shortcut for declaring and initializing a variable in one line (Go uses the value on the right to determine the variable’s type). Taking the long way, you might have written this as:
var message string
message = fmt.Sprintf("Hi, %v. Welcome!", name)
  • In Go, code executed as an application must go in a main package.
package greetings

import (
    "errors"
    "fmt"
)

func Hello(name string) (string, error) {
    if name == "" {
        return "", errors.New("empty name")
    }
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message, nil
}
  • Returns two values: a string and an error. Your caller will check the second value to see if an error occurred. (Any Go function can return multiple values.)
  • Import the Go standard library errors package so you can use its errors.New function.
    • The errors.New function returns an error with your message inside.
  • Add nil (meaning no error) as a second value in the successful return. That way, the caller can see that the function succeeded.
package main

import (
    "fmt"
    "log"
    "ninegene.com/greetings"
)

func main() {
    log.SetPrefix("greetings: ")
    log.SetFlags(0)

    message, err := greetings.Hello("")

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(message)
}
  • Configure the log package to print the command name (“greetings: “) at the start of its log messages, without a time stamp or source file information.
$ go run hello.go
greetings: empty name
exit status 1
  • That’s essentially how error handling in Go works: Return an error as a value so the caller can check for it.

Leave a Comment

Your email address will not be published. Required fields are marked *