1

I have some php code which I'm trying to migrate to Golang code. This is it:

Code in PHP:

class AuditProcessor {
    public function __construct( BfsBlockChain $Bfs ) 
    {
        $this->bfs = $bfs;
    }

I know this is a class, and there is a function inside of it. My question is: in Golang, can I have a function inside my struct? Or how can I replace the code, or format it?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
simón
  • 27
  • 2
  • 2
    Please take some time to walk through [the introduction tour of go](https://go.dev/tour/), methods and function types are covered relatively early on [here](https://go.dev/tour/methods/1) – Elias Van Ootegem Aug 30 '22 at 12:26

1 Answers1

3

You can have fields of function type, and you can also have methods. To fields you can assign any function values (with matching signature), methods are not changeable.

For example:

type Foo struct {
    Bar func() // This is a regular field of function type
}

func (f Foo) Baz() { // This is a method of Foo
    fmt.Println("I'm Baz()")
}

Testing it:

func main() {
    f := Foo{
        Bar: func() { fmt.Println("I'm Bar()") },
    }

    f.Bar()
    f.Baz()

    f.Bar = Bar2
    f.Bar()
}

func Bar2() {
    fmt.Println("I'm Bar2()")
}

Output (try it on the Go Playground):

I'm Bar()
I'm Baz()
I'm Bar2()

See related: Functions as the struct fields or as struct methods

icza
  • 389,944
  • 63
  • 907
  • 827