GoLang Day 3: Error and Random Numbers

⌂ home      ⇧ one level up
Wed Jan 11, 2023 · 241 words · 2 min

Returning errors

Starting today from Return and handle an error.

Tutorial suggests code, something like below

func Hello(name string) (string, error) {
    // If no name was given, return an error with a message.
    if name == "" {
        return "", errors.New("empty name")
    }

    // Return a greeting that embeds the name in a message.
    message := fmt.Sprintf("Hi, %v. Welcome!", name)
    return message, nil
}

Gives off ferric oxide smell *points to Rust's Result type.

So you're returning two values from a function. One is the actual data, other the error. One of them will be nil depending on whether the function executed correctly or not. Sounds simple? This sounds like the hack and patch error handling solution I used in C++ during school days. (I used to create a struct and return that)

The invoker needs to bully themselves with a conditional.

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

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

Not bad. Maybe I'm cringing out only because they chose to keep it simple and predictable and not reinvent the wheel XD

Random Numbers

From Return a random greeting

Seeding is pretty simple.

func init() {
    rand.Seed(time.Now().UnixNano())
}

If you use this function directly, it'll automatically seed the random number generator. init() functions are called automatically by Go.

rand.Intn(n) returns you a random integer lower than n.

Next post onwards I'll be doing some programming using basic constructs.


blog · about · resume · github · kde invent · endeavour · twitter · email · home

🚀❤️️🍰