Skip to main content
eLearner.app
Module 3 · Lesson 1 of 511/50 in the course~10 min
Module lessons (1/5)

Signature and parameters

In Go, functions are declared with func. The signature syntax differs from C/Java: the type goes after the parameter name, separated by a space. It's a choice that reads better out loud — "n of type int" instead of "int n".

Basic syntax

Go
func sum(a int, b int) int {
    return a + b
}

func greet(name string) {
    fmt.Println("ciao", name)
}

A function with no return value simply omits the return type.

Consecutive parameters of the same type

If multiple consecutive parameters share the same type, you can declare it just once on the last one. It's idiomatic and you'll see it everywhere:

Go
func sum(a, b int) int { return a + b }
func max3(a, b, c float64) float64 { /* ... */ }
func parse(s, sep string, limit int) []string { /* ... */ }

Exported vs unexported functions

In Go, visibility is determined by the name: identifiers that start with an uppercase letter are exported (visible from other packages), the others are private to the package.

Go
func Sum(a, b int) int { ... }    // esportata
func helper() { ... }              // privata al package

Functions as values

Functions are first-class values: you can assign them, pass them, and return them. We'll dig deeper in the lesson on closures.

Go
op := sum            // op ha tipo func(int, int) int
fmt.Println(op(2, 3)) // 5

main and init: two special names

  • func main() is the entry point of the main package. No arguments, no return values.
  • func init() is called automatically at package startup (even multiple times if several files define one). Useful for setup; use it sparingly.

Try it

Exercise#go.m3.l1.e1
Attempts: 0Loading…

Define a function sum(a, b int) int that returns a+b, then call it in main with (3, 4).

Loading editor…
Show hint

Shared type: `(a, b int)`. Return type goes AFTER the parentheses.

Solution available after 3 attempts

Exercise#go.m3.l1.e2
Attempts: 0Loading…

Define greet(name string) (no return value) that prints 'ciao <name>'.

Loading editor…
Show hint

No return type if the function returns nothing.

Solution available after 3 attempts

Quiz#go.m3.l1.e3
Ready

Where does the parameter type go in Go?

Go
func f(? ?) {}
Answer options

Recap

  • func name(param type, ...) returnType { ... }.
  • Type after the name; consecutive parameters of the same type → declare it just once.
  • Uppercase initial = exported; lowercase = private to the package.
  • Functions are first-class (assignable, passable).
  • main and init are reserved names with special semantics.