Lesson 10 of 38 · Functions
Go Functions: Parameters and Return Values
In chapter 1 you filled in function bodies that were handed to you. Now you will write your own. A function is a named, reusable piece of logic: you write it once, give it a name that says what it does, and call it wherever you need it.
Real Go programs are built from many small functions, each with one clear job. Because a function takes inputs and returns an output, it can be tested on its own — exactly what the hidden tests in this course do.
Declaring and calling a function
package main
import "fmt"
// add returns the sum of a and b.
func add(a int, b int) int {
return a + b
}
func main() {
total := add(2, 3)
fmt.Println(total, add(total, 10))
}
5 15
Read the signature func add(a int, b int) int from left to right: the keyword func, the name, the parameters in parentheses — each a name followed by its type, just like a var declaration — and finally the result type. Inside the body, return hands a value back to the caller and ends the function immediately.
When consecutive parameters share a type, write the type once: func add(a, b int) int. A function without a result type, like main, returns nothing. The order of declarations doesn't matter: main can call a function declared further down the file.
Go has no default parameter values, no overloading and no keyword arguments. Every call passes every argument, in order, with exactly the declared types. Call sites are a little longer, but never surprising.
Guard clauses: return early
Because return ends the function, you can handle the special cases first and get them out of the way. These guard clauses keep the main logic unindented, with no else blocks:
// Discount returns price with percent % taken off. A percent of 0 or
// less changes nothing; 100 or more makes the item free.
func Discount(price float64, percent int) float64 {
if percent <= 0 {
return price
}
if percent >= 100 {
return 0
}
return price * float64(100-percent) / 100
}
func main() {
fmt.Println(Discount(80, 25), Discount(80, 0), Discount(80, 150))
}
60 80 0
The last line needs no if: when execution reaches it, every special case has already returned.
Arguments are copies
Go passes arguments by value: each parameter is a fresh copy of the argument, so changing it inside the function does not affect the caller.
func reset(score int) {
score = 0 // changes only the local copy
}
func main() {
score := 42
reset(score)
fmt.Println(score)
}
42
If a function should produce a new value, return it and let the caller assign it: score = addBonus(score). (Pointers, coming in a later chapter, let a function change the caller's variable on purpose.)
Exported names and doc comments
A name that starts with a capital letter is exported — other packages can use it. That's why you call fmt.Println, and why fmt.println doesn't exist. Lowercase names like add stay private to their package. The functions in your assignments are exported, like the public API of a small library.
Put a doc comment directly above every exported function, as in Discount above. By convention it is a full sentence that starts with the function's name; editors show it on hover and go doc turns it into documentation. A clear name, typed parameters and one good comment tell callers everything they need without reading the body.
Common mistakes
- Missing return: a function with a result type must end in a
return. If it ends with anif/else ifchain that has no finalelse, the compiler stops withmissing return— even when you know one branch always runs. - Passing the wrong type: after
w := 3, the callArea(w, 4)doesn't compile —wis anint, and Go never converts it tofloat64for you. WriteArea(float64(w), 4). Plain number literals likeArea(3, 4)are fine. - Expecting a parameter change to reach the caller: Go copied the argument.
- Printing instead of returning:
fmt.Printlnshows a value to a human, but the caller — and the tests — get nothing back. Return the value and letmaindo the printing.
Assignment
Write four small functions:
Area(width, height float64) float64returns the area of a rectangle.Greeting(name string, hour int) stringgreetsnameaccording to the hour of the day (0–23):"Good morning, Ann!"whenhouris before 12,"Good afternoon, Ann!"when it is before 18, and"Good evening, Ann!"otherwise.IsLeapYear(year int) boolreports whetheryearis a leap year: years divisible by 4 are leap years, except century years (divisible by 100), which are leap years only when they are also divisible by 400.DaysInYear(year int) intreturns366for a leap year and365otherwise. CallIsLeapYearinstead of repeating the rule.
Area(2.5, 4) // 10
Greeting("Ann", 9) // "Good morning, Ann!"
Greeting("Bo", 18) // "Good evening, Bo!"
IsLeapYear(2000) // true: divisible by 400
IsLeapYear(1900) // false: a century not divisible by 400
DaysInYear(2024) // 366
Return the results — don't print them.
Premium lesson
Unlock the full Learn Go course
- All 38 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Functions and methods in other languages
- JavaScript Functions: Parameters and Return Values · JavaScript
- Python Functions: def, Parameters and return · Python
- Java Methods: Parameters and Return Values · Java
- C# Methods: Parameters and Return Values · C#
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .