Coding for All
Lesson 24: Inputs and Return
Inputs and Return Give a function inputs and get an answer back.
1package main
2
3import "fmt"
4
5func add(a int, b int) int {
6 return a + b
7}
8
9func main() {
10 fmt.Println(add(2, 3))
11 fmt.Println(add(10, 20))
12}
Terminal
$ go run main.go
5
30
Every line, explained
package main
Every Go file starts by saying which package it belongs to. package main means "this is a program you can run", and Go will look inside it for func main.
import "fmt"
import brings in a package from Go's standard library. "fmt" (short for format) is the one full of printing tools, like fmt.Println.
func add(a int, b int) int {
func defines a function: a named block of code. Functions live at the top level of the file, next to main (never inside it). Go doesn't care about their order, but putting helpers first reads nicely top-to-bottom. In Go, types come AFTER names: a int means "a, which is an int". The lone int after the brackets is the type of the answer the function hands back.
return a + b
return hands the value back to whoever called the function, and the function ends. Calling add(2, 3) is like asking a question and getting 5 as the answer.
}
This } closes the function.
func main() {
func main() { ... } is where a Go program starts. When you run the program, Go finds func main inside package main and runs everything between its braces, top to bottom.
fmt.Println(add(2, 3))
add(2, 3) runs the function with a as 2 and b as 3, and becomes its returned value: 5. Then fmt.Println prints it.
fmt.Println(add(10, 20))
Same function, different inputs, different answer: 30.
}
This closing brace } ends func main.