Back to Blog

Functions (Parameters, Returns & Separate Files) - Go Tutorial for Beginners #11

Sandy LaneSandy Lane

Video: Functions (Parameters, Returns & Separate Files) - Go Tutorial for Beginners #11 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Functions (Parameters, Returns & Separate Files) in Go

Functions are fundamental in Go for creating reusable and organized code. This tutorial covers declaring functions with parameters, returning single or multiple values, using named return values for clarity, and organizing functions across multiple files within the same package.

Code

package main

import "fmt"

// Basic function with a single parameter
func greet(name string) {
  fmt.Println("Hello,", name)
}

// Function with multiple parameters and a single return value
func add(a, b int) int {
  return a + b
}

// Function returning multiple values (quotient and remainder)
func divmod(a, b int) (int, int) {
  return a / b, a % b
}

// Named return values for clarity and documentation
func rectangle(w, h float64) (area, perimeter float64) {
  area = w * h
  perimeter = 2 * (w + h)
  return // returns named values automatically
}

func main() {
  greet("Alice")

  sum := add(5, 7)
  fmt.Println("Sum:", sum)

  quotient, remainder := divmod(17, 4)
  fmt.Println("Quotient:", quotient, "Remainder:", remainder)

  a, p := rectangle(3.0, 4.0)
  fmt.Printf("Area: %.2f, Perimeter: %.2f\n", a, p)
}

Key Points

  • Functions in Go are declared with the func keyword, specifying parameters and return types.
  • Go supports multiple return values, which is useful for returning results and errors simultaneously.
  • Named return values improve readability and allow implicit returns without specifying variables explicitly.
  • Functions can be organized into separate files within the same package for better code structure without import statements.
  • Using functions promotes code reuse and clearer program logic.