简体   繁体   中英

Can I have a function inside my struct? Converting from PHP class

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM