Courses/Go/Functions and Methods

    Lesson 3 • Beginner

    Functions and Methods 🐹

    Define functions with multiple return values, closures, variadic parameters, and attach methods to your own types.

    What You'll Learn in This Lesson

    • • Function syntax and multiple return values
    • • Closures and functions as values
    • • Variadic functions with ...T
    • • Methods with value and pointer receivers
    • defer, panic, and recover

    1️⃣ Function Basics

    Go functions can return multiple values — this is the foundation of Go's error handling pattern. Named return values let you use "naked returns" for cleaner code in simple functions.

    Try It: Functions

    Multiple returns, named returns, and parameter shorthand

    Try it Yourself »
    JavaScript
    // Functions in Go
    console.log("=== Function Syntax ===");
    console.log();
    console.log("func greet(name string) string {");
    console.log('    return "Hello, " + name + "!"');
    console.log("}");
    console.log();
    
    function greet(name) { return "Hello, " + name + "!"; }
    console.log("greet(\"Alice\") →", greet("Alice"));
    console.log();
    
    console.log("=== Multiple Parameters (Same Type Shorthand) ===");
    console.log("func add(a, b int) int {    // Both are int");
    console.log("    return a + b");
    console.log
    ...

    2️⃣ Closures & Variadic Functions

    Functions in Go are first-class values — assign them to variables, pass them around, and return them from other functions. Closures capture variables from their enclosing scope. Variadic functions accept any number of arguments.

    Try It: Closures

    Function values, closures, and variadic parameters

    Try it Yourself »
    JavaScript
    // Closures & Function Values
    console.log("=== Functions as Values ===");
    console.log("In Go, functions are first-class citizens.");
    console.log();
    
    console.log("// Assign function to variable:");
    console.log("double := func(n int) int { return n * 2 }");
    const double = n => n * 2;
    console.log("double(5) →", double(5));
    console.log();
    
    console.log("=== Closures ===");
    console.log("func counter() func() int {");
    console.log("    count := 0");
    console.log("    return func() int {");
    console.log(" 
    ...

    3️⃣ Methods

    Methods are functions with a receiver — they belong to a type. Use value receivers for read-only methods and pointer receivers when you need to modify the struct or for large types (avoids copying).

    Try It: Methods

    Value vs pointer receivers and method patterns

    Try it Yourself »
    JavaScript
    // Methods — Functions Attached to Types
    console.log("=== Methods in Go ===");
    console.log("A method is a function with a receiver argument.");
    console.log();
    
    console.log("type Rectangle struct {");
    console.log("    Width  float64");
    console.log("    Height float64");
    console.log("}");
    console.log();
    console.log("// Method with value receiver");
    console.log("func (r Rectangle) Area() float64 {");
    console.log("    return r.Width * r.Height");
    console.log("}");
    console.log();
    console.log("// Meth
    ...

    4️⃣ Defer, Panic, Recover

    defer guarantees cleanup code runs when a function exits — essential for closing files, connections, and mutexes. Deferred calls execute in LIFO order. panic/recover handle truly exceptional situations.

    Try It: Defer & Panic

    Cleanup with defer and crash recovery

    Try it Yourself »
    JavaScript
    // Defer, Panic, and Recover
    console.log("=== defer — Delayed Execution ===");
    console.log("defer schedules a function to run AFTER the surrounding");
    console.log("function returns. Perfect for cleanup!");
    console.log();
    
    console.log("func readFile(path string) {");
    console.log('    f, err := os.Open(path)');
    console.log("    if err != nil { return }");
    console.log("    defer f.Close()    ← Runs when readFile exits");
    console.log();
    console.log("    // ... read the file ...");
    console.log("    /
    ...

    ⚠️ Common Mistakes

    ⚠️
    Ignoring error returns — Never write result, _ := riskyOp() in production. Always handle errors.
    ⚠️
    Using panic for control flow — Panic is for unrecoverable situations. Use error returns for expected failures.
    💡
    Pro Tip: Defer is evaluated immediately but executed later. defer fmt.Println(x) captures x's current value, not its value at function exit.

    📋 Quick Reference

    PatternGo Syntax
    Functionfunc name(a int) string {}
    Multi-returnfunc f() (int, error) {}
    Variadicfunc sum(nums ...int) int {}
    Methodfunc (r *Rect) Area() float64 {}
    Deferdefer file.Close()

    🎉 Lesson Complete!

    You now master Go functions, methods, and defer! Next, we'll learn structs and interfaces — Go's approach to composition.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service