Functions Returning Errors
Part of the Fundamentals section of Coddy's GO journey — lesson 104 of 109.
In Go, functions commonly return an error as their last return value to indicate if something went wrong.
Create a function that returns both a result and an error:
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}Call the function and handle the error:
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}The output will be:
Error: cannot divide by zeroChallenge
BeginnerIn this challenge, you'll practice creating a function that returns an error when invalid input is provided.
You need to complete the validateUsername function that checks if a username is valid. A username is valid if it's at least 3 characters long. If the username is valid, return nil for the error. If it's invalid, return an error with an appropriate message.
The code to call your function and handle the error is already written for you.
Note: This challenge uses predefined variables instead of user input.
Cheat sheet
Functions in Go commonly return an error as their last return value to indicate if something went wrong.
Create a function that returns both a result and an error:
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}Handle the error when calling the function:
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}Return nil when there's no error, and use errors.New() to create error messages.
Try it yourself
package main
import (
"errors"
"fmt"
)
func validateUsername(username string) error {
// TODO: Check if the username length is less than 3 characters
// If it is, return an error with the message "username too short"
// Otherwise, return nil (no error)
return nil
}
func main() {
// Test with a valid username
validName := "bob123"
err1 := validateUsername(validName)
if err1 != nil {
fmt.Printf("%s is invalid: %v\n", validName, err1)
} else {
fmt.Printf("%s is valid!\n", validName)
}
// Test with an invalid username
invalidName := "ab"
err2 := validateUsername(invalidName)
if err2 != nil {
fmt.Printf("%s is invalid: %v\n", invalidName, err2)
} else {
fmt.Printf("%s is valid!\n", invalidName)
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code11Composite Types: Slices
Introduction to SlicesDeclaring Slice LiteralsCreating Slices with `make`Slice Length vs CapacityAccessing Slice ElementsAppending ElementsSlicing Existing Slices/ArraysIterating Over SlicesCopying SlicesRecap - Dynamic Lists14Basic Error Handling
The Concept of ErrorsThe `error` InterfaceFunctions Returning ErrorsChecking for ErrorsCreating Simple ErrorsCreating Formatted ErrorsBasic Error HandlingRecap - Handling Problems3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions