Ana içeriğe geç
eLearner.app
Modül 3 · Ders 1 ders 5Kurstaki 11/50~10 min
Modül dersleri (1/5)

İmza ve parametreler

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

Egzersiz#go.m3.l1.e1
Denemeler: 0Yükleniyor…

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

Düzenleyici yükleniyor…
İpucu göster

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

3 denemeden sonra çözüm mevcut

Egzersiz#go.m3.l1.e2
Denemeler: 0Yükleniyor…

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

Düzenleyici yükleniyor…
İpucu göster

No return type if the function returns nothing.

3 denemeden sonra çözüm mevcut

Quiz#go.m3.l1.e3
Hazır

Where does the parameter type go in Go?

Go
func f(? ?) {}
Cevap seçenekleri

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.