John Davidson

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?

My Answer:
Yes, you can have a function inside a struct in Golang. Here is an example of how you can define a struct with a function in Golang:

package main

import "fmt"

type AuditProcessor struct {
Bfs *BfsBlockChain

func NewAuditProcessor(bfs *BfsBlockChain) *AuditProcessor {
return &AuditProcessor{Bfs: bfs}

func (ap *AuditProcessor) Process() {
// Add your processing logic here
fmt.Println("Processing audit")

type BfsBlockChain struct {
// Define your BfsBlockChain struct here

func main() {
bfs := &BfsBlockChain{}
ap := NewAuditProcessor(bfs)

In this example, the `AuditProcessor` struct has a function `Process` that can be called on an instance of `AuditProcessor`. The `NewAuditProcessor` function is used to create a new instance of `AuditProcessor` with a `BfsBlockChain` parameter.

Rate this post

4 of 5 based on 7335 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us