Declaring functions and parameters
A function is declared with func, a name, a parameter list and — if it returns something — a result type: func add(a int, b int) int. When neighbouring parameters share a type you can write the type once: func add(a, b int) int. Unlike Python or JavaScript, the types are part of the signature, so the compiler checks every call.
Go keeps functions deliberately plain. There are no default parameter values, no named arguments and no overloading — two functions in one package cannot share a name, even with different parameters. Arguments are always passed by value: the function gets a copy. (Slices, maps and pointers are small values that refer to shared data; Modules 04 and 05 show what that means.)
package main
import "fmt"
func greet(name string) {
fmt.Println("Hello,", name)
}
func add(a, b int) int {
return a + b
}
func area(width, height float64) float64 {
return width * height
}
func main() {
greet("Gopher")
fmt.Println(add(2, 3))
fmt.Printf("%.1f\n", area(2.5, 4))
}Hello, Gopher
5
10.0Write func perimeter(width, height float64) float64 and print the perimeter of the same rectangle.
main can call add even if add is declared further down the file. Package-level functions are visible everywhere in the package, so Go code usually puts main first or last purely by taste.missing return
package main
import "fmt"
func sign(n int) string {
if n > 0 {
return "positive"
} else if n < 0 {
return "negative"
}
}
func main() {
fmt.Println(sign(-4))
}# command-line-arguments
./main.go:11:1: missing returnA function with a result type must end every path with a return. When n is 0, neither branch runs and the function would fall off the end with no value. The compiler does not reason about which numbers are possible — it only sees a path with no return.
Return something on the last path (or end with a plain else that returns).
package main
import "fmt"
func sign(n int) string {
if n > 0 {
return "positive"
} else if n < 0 {
return "negative"
}
return "zero"
}
func main() {
fmt.Println(sign(-4))
}not enough arguments in call
package main
import "fmt"
func add(a, b int) int {
return a + b
}
func main() {
fmt.Println(add(1))
}# command-line-arguments
./main.go:10:18: not enough arguments in call to add
have (number)
want (int, int)With no default values, every call must pass exactly as many arguments as there are parameters. The compiler shows what you passed (have) and what the signature needs (want).
Pass every argument. If a value is often the same, write a second, well-named function that calls the first.
package main
import "fmt"
func add(a, b int) int {
return a + b
}
func main() {
fmt.Println(add(1, 2))
}