functions- part 2

f

Well I already talked about functions in general But there’s more.

This article is gonna cover 3(pun intended) concepts

  • functions as value
  • closures
  • methods
  • recursion

functions as value

well we already know you can store value to a variable. But guess what? You can also store a function inside a variable.

package main

import "fmt"


func main() {
	ref := func () {
		fmt.Println("hi")
	}

	ref()
}

Here first i assigned that function to a variable named ref and then I called ref()

That ref is just a reference, it will act like a function once we call it like ref()

closures

A function can return an another function!

package main

import "fmt"

func hi() func() string{
	a := "hi"
	return func () string{
		return a
	}
}

func main() {
	
	temp := hi()
	fmt.Println(temp()) 
}

To see whats actually happening here, Lets print everything!

package main

import "fmt"

func hi() func() string{
	a := "hi"
	return func () string{
		return a
	}
}

func main() {
	
	temp := hi()
	fmt.Println(hi) 
	fmt.Println(temp) 
	fmt.Println(temp()) 
}
  • hihi function reference
  • temp – as temp = hi() we get the reference of the function that hi() returned
  • temp() – actually returned "hi"

Methods

check the below code. We already talked about structs, So I’m not gonna explain it again.

package main

import "fmt"

type name struct {
	firstName string
	lastName string
}

func greet(nameObj name) {
	fmt.Print("hi ", nameObj.firstName)
}

func main() {
	obj := name {firstName: "vignesh", lastName: "war"}

	greet(obj)
}

This is perfectly fine. But If you already know any OOP language you might prefer obj.greet() to greet(obj)

This is how we can achieve that in GOlang.

package main

import "fmt"

type name struct {
	firstName string
	lastName string
}

func (nameObj name) greet() {
	fmt.Print("hi ", nameObj.firstName)
}

func main() {
	obj := name {firstName: "vignesh", lastName: "war"}

	obj.greet()
}

This is the basic syntax:

func (variable_name type) function_name() {
   // function body
}

Recursion

To be honest, If you already know elementary math, this is nothing new.

(sorry for the handwriting)

So we’re just gonna translate this idea to programming.

package main

import "fmt"

func f(a int) int {
	if a == 1 {
		return 1
	}
	return a * f(a-1)
}

func main() {
	ans := f(4)

	fmt.Println(ans)
}

You can learn kore about this here: https://en.wikipedia.org/wiki/Recursion

Ye! Thats all for today.

Happy reading.

About the author

vigneshwar

Add comment

Leave a Reply

By vigneshwar

Most common tags

%d bloggers like this: