R
R
Roman2020-05-23 15:09:56
go
Roman, 2020-05-23 15:09:56

How to create a method reference from an array-property of a struct in Go?

The task is to make in Go such a structure, one of the properties of which would be an array or a map, with pointers to methods (that is, functions that are executed precisely in the context of an instance of the structure). And there would also be a method, calling which and passing the identifier of the array (map) to it, it would be possible to call a method that could work with properties

. The language is new to me, I could not google it at all.

For example, the same thing, but in JavaScript

class Test {
    constructor() {
        this._a = 0;
        this._b = 0;
        // Список указателей на методы
        this._fn = new Map();
        this._fn.set(0x00, this._add);
        this._fn.set(0x01, this._sub);
    }

    init(a, b) {
        this._a = a;
        this._b = b;
    }

    _add() {
        return this._a + this._b;
    }

    _sub() {
        return this._a - this._b;
    }

    call(fnID) {
        const fn = this._fn.get(fnID);
        if (!fn) {
            throw new Error('Bad function ID');
        }
        return fn.apply(this);
    }
}

const t = new Test();
t.init(2, 5)
console.log(t.call(0x00), t.call(0x01));

// Результат выполнения: 7 -3

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2020-05-23
@r1000ru

Below is the same thing in Go, but without a method map, but I would like it to be somehow prettier:

package main

import "fmt"

// Test structure
type Test struct {
  a       int8
  b       int8
  opcodes [2]func() int8
}

func (t *Test) add() int8 {
  return t.a + t.b
}

func (t *Test) sub() int8 {
  return t.a - t.b
}

// Init properties
func (t *Test) Init(a, b int8) {
  t.a = a
  t.b = b
  // Вручную заполняем указатели на методы
  t.opcodes[0] = t.add
  t.opcodes[1] = t.sub
  return
}

// Call method by ID
func (t *Test) Call(fnID int8) int8 {
  fn := t.opcodes[fnID]
  if fn == nil {
    panic(`Empty command`)
  }
  r := fn()
  return r
}

func main() {
  t := new(Test)
  t.Init(2, 5)
  fmt.Println(t.Call(0x00), t.Call(0x01))
}

UPD: Removed switch, added an array. Accordingly, the question is: is it possible to make it so that when creating an instance, the Test.opcodes array is automatically filled with pointers to methods

A
Alexander Pavlyuk, 2020-05-23
@pav5000

Don't try to drag the style of scripting languages ​​into Go. Here is a different style and a different approach.
It's better to just write in Javascript than to try to make Javascript out of Go.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question