Function Scope Basics
Part of the Fundamentals section of Coddy's GO journey — lesson 58 of 109.
In Go, variables declared inside a function are only accessible within that function. This is called function scope.
Create a function with a local variable:
func calculateTotal(price int, quantity int) int {
tax := 0.1 * float64(price * quantity) // local variable
total := price * quantity + int(tax)
return total
}
func main() {
result := calculateTotal(10, 2)
fmt.Println("Total:", result)
// fmt.Println(tax) // Error: tax is not accessible here
}The output shows only the returned value:
Total: 22The variable tax only exists inside the calculateTotal function and cannot be accessed from main.
Challenge
BeginnerIn this challenge, you'll practice understanding function scope in Go. You need to fix a simple program that has a scope issue.
The program has a global variable message and a function that tries to modify it. Your task is to fix the code so that the function properly updates the global variable.
Cheat sheet
Variables declared inside a function are only accessible within that function (function scope):
func calculateTotal(price int, quantity int) int {
tax := 0.1 * float64(price * quantity) // local variable
total := price * quantity + int(tax)
return total
}
func main() {
result := calculateTotal(10, 2)
fmt.Println("Total:", result)
// fmt.Println(tax) // Error: tax is not accessible here
}Local variables exist only within their function and cannot be accessed from outside.
Try it yourself
package main
import "fmt"
// Global variable
var message string = "Hello from global scope"
func updateMessage() {
// This creates a new local variable instead of modifying the global one
message := "Hello from function scope"
fmt.Println("Inside function:", message)
}
func main() {
fmt.Println("Before function call:", message)
updateMessage()
// TODO: The global message is still the original value
// Modify the updateMessage() function to change the global variable
fmt.Println("After function call:", message)
}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