Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

IIF or Immediately Invoked Function in Go (Golang)

Posted on March 6, 2023March 6, 2023 by admin

Table of Contents

  • Overview:
  • Use Case
  • Code:

Overview:

IIF or Immediately Invoked Function are those function which can be defined and executed at the same time. A function can be invoked immediately by appending a () after the end brace of the function.

Use Case

One of the uses of the IIF function is when you don’t want to expose the logic of the function either within or outside the package. For eg let’s say there is a function which is setting some value. You can encapsulate all the logic of setting in an IIF function. This function won’t be available for calling either outside or within the package.

Code:

Let’s see the working code. The function which computes the square of 2 is immediately invoked by having () at the end and the returned value is assigned to the variable squareOf2.

package main
import "fmt"
func main() {
squareOf2 := func() int {
return 2 * 2
}()
fmt.Println(squareOf2)
}

Output:

2
  • golang
  • iif
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2024 Welcome To Golang By Example | Design: Web XP