Build Your Own Functions

Build Your Own Functions

Build Your Own Functions

So far, all your code has lived inside main(). That works for small programs, but what happens when you need the same logic in multiple places?

example.go
// before uploading...
if fileSizeMB > bandwidthMB { fmt.Println("too large") }

// before downloading...
if fileSizeMB > bandwidthMB { fmt.Println("too large") }

If you need to change how the check works, you have to update every copy. Functions solve this. You write the logic once, give it a name, and call it wherever you need it.

Anatomy of a function

example.go
func remainingSpace(diskMB, fileMB int) int {
    return diskMB - fileMB
}

left := remainingSpace(1000, 350) // left is 650
Part Example What it does
Keyword func Tells Go you're defining a function
Name remainingSpace How you call this function later
Parameters (diskMB, fileMB int) Inputs the function needs. Order matters: 1000 goes to diskMB, 350 goes to fileMB
Return type int The type of value the function gives back
return return diskMB - fileMB Sends a value back to the caller and exits the function. Must match the return type

If two parameters share a type, you only write it once: diskMB, fileMB int instead of diskMB int, fileMB int.

Functions aren't limited to integers, and they don't have to subtract. Here's one that takes a string and returns a string:

example.go
func fullPath(dir, file string) string {
    return dir + "/" + file
}

path := fullPath("/var/log", "server.log") // path is "/var/log/server.log"

Whatever types and operations the job needs, that's what goes inside.

Not every function returns something. If there's no return type, you don't need the return keyword at all:

example.go
func logTransfer(filename string) {
    fmt.Println("Transferring:", filename)
}
>_Exercise

Exercise: Download Time Calculator

Write a function called downloadTime(fileSizeMB, speedMBps int) int where fileSizeMB is the file size in megabytes and speedMBps is the download speed in megabytes per second.

If the speed is zero or negative, return -1 to signal an invalid speed. Otherwise, return fileSizeMB / speedMBps.

Examples:

  • downloadTime(500, 50)10
  • downloadTime(1000, 100)10
  • downloadTime(100, 0)-1 (can't divide by zero)
Stuck? Reveal a hint to help you.
Hints (0/3)
Key Takeaway
Next UpFunctions that return more than one value.