Initial commit - learning the basics

This commit is contained in:
V
2025-08-30 13:55:18 +01:00
commit 194ca9b7a9
27 changed files with 830 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
module learning.local/using_modules
go 1.24.5
+54
View File
@@ -0,0 +1,54 @@
package using_modules
import (
"fmt"
"errors"
"math/rand"
)
// 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 "", errors.New("empty name")
}
message := fmt.Sprintf(randomFormat(), name)
return message, nil
}
// Hellos retruns 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 terieved message with
// the name.
messages[name] = message
}
return messages, nil
}
// 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 a randomly selected message format by specifying
// a random index for the slice of formats.
return formats[rand.Intn(len(formats))]
}
+26
View File
@@ -0,0 +1,26 @@
package using_modules
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.Errorf(`Hello("Gladys") = %q, %v, want match for %#q, nill`, msg, err, want)
}
}
// TestHelloEmpty calls greeting.Hello with an empty string,
// checking for an error
func TestHelloEmpty(t *testing.T) {
msg, err := Hello("")
if msg != "" || err == nil {
t.Errorf(`Hello("") = %q, %v, want "", error`, msg, err)
}
}