मुख्य सामग्री पर जाएं
eLearner.app
मॉड्यूल 3 · पाठ 1 का 5पाठ्यक्रम में 11/50~10 min
मॉड्यूल पाठ (1/5)

हस्ताक्षर और पैरामीटर

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

व्यायाम#go.m3.l1.e1
प्रयास: 0लोड हो रहा है...

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

संपादक लोड हो रहा है...
संकेत दिखाएँ

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

3 प्रयासों के बाद समाधान उपलब्ध है

व्यायाम#go.m3.l1.e2
प्रयास: 0लोड हो रहा है...

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

संपादक लोड हो रहा है...
संकेत दिखाएँ

No return type if the function returns nothing.

3 प्रयासों के बाद समाधान उपलब्ध है

Quiz#go.m3.l1.e3
तैयार

Where does the parameter type go in Go?

Go
func f(? ?) {}
उत्तर विकल्प

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.