Function declaration syntax: things in parenthesis before function name in Go

In Go, the syntax for declaring a function is func functionname(parametername type) returntype { }. The function declaration starts with a func keyword followed by the functionname, and the parameters are specified between ( ) followed by the returntype of the function.

In the parenthesis before the function name, you can declare zero or more parameters the function will accept. Each parameter consists of a parameter name followed by its type.

After the parameter list, you can specify the function’s return type. This can be any valid type or void if the function does not return a value.

However, Go also has a unique feature where you can attach a function to a receiver. This allows you to define methods on custom types (similar to object-oriented programming).

Syntax

func (receiver receiverType) functionName(parameters) returnType {
   // function body
}

In this syntax, receiverType is a type (often a struct type), and receiver is a variable representing an instance of that type within the function.

Example

package main

import (
  "fmt"
)

type Person struct {
  Name string
  Age int
}

func (p Person) SayHello() {
  fmt.Println("Hello, my name is", p.Name)
}

func main() {
  // Creating an instance of the Person struct
  person := Person{
    Name: "Krunal",
    Age: 30,
  }

  // Calling the SayHello method
  person.SayHello()
}

Output

Hello, my name is Krunal

The main() function creates an instance of the Person struct and then calls the SayHello() method on that instance.

That’s it!

Leave a Comment