Premium Tutorials • Books • Articles • Modern Programming Paths Go Programming Book · Author Bookstore
Lesson 8 of 15

Functions in Go

Organize code into reusable blocks using functions.

Beginner Friendly Runnable Example Go Programming
Learning objective: Create functions with parameters and return values.

Creating Functions

A function is a reusable block of code. Functions make programs easier to organize, test, and maintain.

Parameters

Parameters allow a function to receive values from the caller.

Return Values

A function can return one or more values. Go functions often return a result and an error.

Example Code

Create or update your Go file, then run the program using go run main.go.

package main

import "fmt"

func add(a int, b int) int {
    return a + b
}

func greet(name string) {
    fmt.Println("Hello,", name)
}

func main() {
    greet("Alex")
    result := add(5, 7)
    fmt.Println("Result:", result)
}
Key points to remember
  • Function names should describe what the function does.
  • Keep beginner functions short and focused.
  • Use return to send a value back to the caller.

Practice Exercises

  1. Create a function that multiplies two numbers.
  2. Create a function that prints a welcome message.
  3. Create a function that returns the larger of two numbers.

Continue Learning

After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.