Go: Using a Closure in Place of a Struct

Go: Using a Closure in Place of a Struct

Go: Using a Closure in Place of a Struct. Let's look at using a closure where we'd idiomatically use a struct. We will implement a Fibonacci Number sequence generator two ways, once with a struct and once with a closure.

This note isn’t suggesting a pattern to follow, it’s a thought exercise. Let’s look at using a closure where we’d idiomatically use a struct.

A Fibonacci Number Sequence Generator

For this thought exercise, we will implement a  Fibonacci Number sequence generator two ways, once with a struct and once with a closure. We’ll use the same approach in both to compare.

As a Structure

So here’s a simple and idiomatic implementation with a struct:

package main

import "fmt"
type Fibonacci struct {
  x1, x2 int
}
func NewFibonacci() *Fibonacci {
  return &Fibonacci{-1,1}
}
func (f *Fibonacci) Next() int {
  f.x1, f.x2 = f.x2, f.x1 + f.x2
  return f.x2
}
func main() {
  f := NewFibonacci()
  for i := 0; i < 10; i++ {
    fmt.Println(f.Next())
  }
}

go golang closures-functions

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

What's new in the go 1.15

Go announced Go 1.15 version on 11 Aug 2020. Highlighted updates and features include Substantial improvements to the Go linker, Improved allocation for small objects at high core counts, X.509 CommonName deprecation, GOPROXY supports skipping proxies that return errors, New embedded tzdata package, Several Core Library improvements and more.

Go Functions Tutorial With Example | Introduction to Functions in Golang

Go Functions Tutorial With Example | Introduction to Functions in Golang. A function is a group of statements that together perform a task.

Go Functions Tutorial With Example | Introduction to Functions in Golang

Go Functions Tutorial With Example | Introduction to Functions in Golang. A function is a group of statements that together perform a task.

Go Functions Tutorial With Example | Introduction to Functions in Golang

Go Functions Tutorial With Example | Introduction to Functions in Golang. A function is a group of statements that together perform a task.

Golang Receiver Function Example | Go Function Receivers

Golang Receiver Function Example | Go Function Receivers. You can set a method on the new typed variable, and that method is Receiver function.