Understanding Functions
Part of the Fundamentals section of Coddy's GO journey — lesson 51 of 109.
Functions are reusable blocks of code that perform specific tasks. They help organize code and avoid repetition.
Let's create a simple function that adds two numbers:
func add(x int, y int) int {
return x + y
}
func main() {
result := add(5, 3)
fmt.Println("5 + 3 =", result)
}After executing this code, the number 8 will show on the screen as the result of adding 5 and 3:
5 + 3 = 8Let's break down how to define a function:
First, we declare the function with a name and parameters:
func add(x int, y int) int {This creates a function named add that takes two integer parameters and returns an integer value.
Next, let's write the function body that performs the calculation:
return x + yThis simple line adds the two parameters together and sends the result back to wherever the function was called.
Now, let's see how to call our function and use the result:
result := add(5, 3)This line calls our add function with the values 5 and 3, and stores the returned value (8) in a new variable called result.
Finally, let's display the result to the user:
fmt.Println("5 + 3 =", result)This prints the text "5 + 3 =" followed by the value stored in result, which is 8.
Challenge
BeginnerIn this challenge, you'll practice creating and using a simple function in Go.
Your task is to complete the greet function that takes a name as a parameter and returns a greeting message.
The function should return a string in the format: "Hello, " + name + "!"
The function should return a string in the format: "Hello, Gopher!"
Cheat sheet
Functions are reusable blocks of code that perform specific tasks. They help organize code and avoid repetition.
Function syntax:
func functionName(parameter type) returnType {
// function body
return value
}Example function that adds two numbers:
func add(x int, y int) int {
return x + y
}Calling a function and storing the result:
result := add(5, 3)
fmt.Println("5 + 3 =", result) // Output: 5 + 3 = 8Try it yourself
package main
import "fmt"
// TODO: Complete the greet function that takes a name parameter
// and returns a greeting string in the format: "Hello, " + name + "!"
// Example: if name is "Gopher", return "Hello, Gopher!"
func greet(name string) string {
// Your code here
}
func main() {
// Test the function with a predefined name
name := "Gopher"
message := greet(name)
fmt.Println(message)
// Expected output: Hello, Gopher!
}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 Code3Basic 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