Skip to content

tour: add example for together named returns and defer functions #1724

Description

@salihdev0

Named Returns Context: https://go.dev/tour/basics/7

Defer Functions Context: https://go.dev/tour/flowcontrol/12

Named returns are much more valuable with the value. There are also nice use cases where they can be used together in real life. An example can be added where the two are together, as follows:

package main

import (
	"errors"
	"fmt"
)

func main() {
	if err := runDatabaseTransaction(); err != nil {
		fmt.Println("Error:", err)
	}
}

func runDatabaseTransaction() (err error) {
	defer func() {
		if err != nil {
			fmt.Println("an error occurred:", err)
			// Handle the error, e.g., rollback the transaction
		}
	}()
	err = errors.New("index out of range") // Simulating an error
	if err != nil {
		return err
	}
	return nil
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions