Skip to main content

Command Palette

Search for a command to run...

Go - Function

Published
3 min read
Go - Function
S

🖐Hi There! ⫸ Currently working as a System Administrator | WebLogic Admin. ⫸ Aspiring to be DevOps | SRE | Build & Release Engineer ⫸Enthusiast about Technical Writing

Introduction

  1. self contained units of code which carry out a certain job.

  2. help us divide a program into small manageable, repeatable and organizable chunks.

Why use function

  1. Reusability

  2. Abstraction

Function Syntax

 func () {
  // body of the function
  }

Example:-

 func addNumbers(a int, b int) int {
 // body of the function
 }

return keyword

return from method when it execution is complete

 func addNumbers(a int, b int) int {
 sum := a + b
 return sum
 }

calling a function

 function_name()
  add Numbers(2, 3)
  sumOfNumbers := addNumbers(2, 3)

naming convention for functions

  1. must begin with a letter

  2. can have any number of additional letters

  3. cannot contain spaces.

  4. case-sensitive.

parameter vs arguments

Function Parameter are the names listed in the function definition. Function arguments are the real values passed into the function.

 func addNumbers(a int, b int) int {
 sum := a + b
 return sum
 }
 func main() {
 sumOfNumbers := addNumbers(2, 3)
 fmt.Print(sumOfNumbers)
 }

main.go

 package main
 import "fmt"

 func printGreeting(str string) {
      fmt.Println("Hey there,", str)
 }
 func main() {
      printGreeting("Shounak")
 }

 >>> go run main.go
 Hey there, Shounak

Return Type

returning single value

variadic functions

  1. function that accepts variables number of arguments.

  2. it is possible to pass a varying number of arguments of the same type as referenced in the function signature.

  3. to declare a variadic function, the type of the final parameter is preceded by an ellipsis "..."

  4. Example - fmt.Println method

  func  (param-1 type, param-2 type, para-3 ...type)
  func sumNumbers(numbers ...int) int
  func sumNumbers(str string, numbers ...int)

main.go

  package main
  import "fmt"
  func sumNumbers(numbers ...int) int{
        sum := 0
        for _, value := range numbers {
            sum += value
        }
        return sum
  }
  func main() {
        fmt.Println(sumNumbers())
        fmt.Println(sumNumbers(10))
        fmt.Println(sumNumbers(10, 20))
        fmt.Println(sumNumbers(10, 20, 30, 40, 50))
  }
  >>> go run main.go
      0
      10
      30
      150

blank identifier '_'

main.go

  package main
  import "fmt"
  func f() (int, int) {
        return 42, 53
  }
  func main() {
        v , _ := f()
        fmt.Println(v)
  }

  >>> go run main.go
      42

Recursive Functions

  1. recursion is a concept where a function calls itself by direct or indirect means.

  2. the function keeps calling itself until it reaches a base case.

  3. used to solve a problem where the solution is dependent on the smaller instance of the same problem.

Example to calculate factorial of number factorial(5) = 54321

main.go

  package main
  import "fmt"
  func factorial(n int )int{
      if n == 1 {
          return 1
  }
    return n * factorial(n-1)
  }
  func main() {
    n := 5
    result := factorial(n)
    fmt.Println("Factorial of", n, "is :", result)

  >>> go run main.go
      Factorial of 5 is : 120

Anonymous Function

  1. An anonymous function is a function that is declared without any named identifier to refer to it.

  2. They can accept inputs and return outputs, just as standard functions do.

  3. They can be used for containing functionality that need not be named and possibly for short-term use.

main.go

  package main
  import "fmt"
  func main () {
      x := func (1 int, b int) int {
          return 1 * b
      }
      fmt.Printf("%T \n", x)
      fmt.Println(x(20, 30))
  }

  >>> go run main.go
      func(int, int) int
      600

High Orders Functions

  1. function that receives a function as an argument or returns a function as output

why use high order function

  1. Composition

  2. creating smaller functions that take care of certain piece of logic.

  3. composing complex function by using different smaller functions.

  4. Reduces bugs

  5. Code gets easier to read and understand

That's great if you have make till here you have covered basic of Golang Function.

If you liked what you read, do follow and any feedback for further improvement will be highly appreciated!

Thank you and Happy Learning!👏

More from this blog

Shounak Khulape

41 posts