Learning Go from Documentation #4 (Return a random greeting)

Kuzey Köse
2 min readDec 24, 2021

In this blog, we will learn how to use Go slice. This is 4th blog which continues with documentation. We will use folders that we created at #3 blog. Let’s start.

Firstly open the greetings folder, then greetings.go file. Starting a small slice to learning how it works is our target. Let’s create a three greeting messages and return one of the messages randomly. Also, we need to math/rand and time package.

package greetingsimport (
"errors"
"fmt"
"math/rand"
"time"
)
func Hello(name string) (string, error) {
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 {
formats := []string{
"Hi, %v. Welcome!",
"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))]
}

Go executes init functions automatically at program startup, after global variables have been initialized.

We added a randomFormat function. This function selects randomly a format in formats slices. Math/rand package used for generating a random number with rand. Besides, the init function seeds the rand package with the current time.

Array: An array’s length is part of its type, so arrays cannot be resized.

Slices: An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.

We have done the greeting.go file. Let’s continue with the Hello folder. This file doesn’t have any changes. Because our greeting.go is manage our greeting.Hello function. In the Error handling blog, we removed the string in greetings.Hello. Now, we will add “Kuzey”.

// hello.go
package main
import (
"fmt"
"log"
"example.com/greetings"
)
func main() {
log.SetPrefix("greetings: ")
log.SetFlags(0)
// Request a greeting message.
message, err := greetings.Hello("Kuzey")
if err != nil {
log.Fatal(err)
}
fmt.Println(message)
}

Then, run the code multiple times the see a randomly selected greeting.

// terminal
// cd -hello folder
$ go run .
Hi, Kuzey. Welcome!
$ go run .
Hi, Kuzey. Welcome!
$ go run .
Hail, Kuzey! Well met!

This blog post is personal notes 🙂 If you are more interested in it, you need to check https://go.dev/doc/tutorial/random-greeting site.

--

--