Home > Net >  Interface management in Go
Interface management in Go

Time:11-22

I know this has been asked in various forms many times before but I just can't seem to implement what I'm learning in the way that I need. Any help is appreciated.

I have a series of exchanges which all implement roughly the same APIs. For example, each of them have a GetBalance endpoint. However, some have one or two unique things which need to be accessed within the functions. For example, exchange1 needs to use a client when calling it's balance API, while exchange2 requires both the client variable as well as a clientFutures variable. This is an important note for later.

My background is normal OOP. Obviously Go is different in many ways, hence I'm getting tripped up here.

My current implementation and thinking is as follows:

In exchanges module

type Balance struct {
    asset       string
    available   float64
    unavailable float64
    total       float64
}

type Api interface {
    GetBalances() []Balance
}

In Binance module


type BinanceApi struct {
    key           string
    secret        string
    client        *binance.Client
    clientFutures *futures.Client
    Api           exchanges.Api
}

func (v *BinanceApi) GetBalance() []exchanges.Balance {
    // Requires v.client and v.clientFutures
    return []exchanges.Balance{}
}

In Kraken module


type KrakenApi struct {
    key           string
    secret        string
    client        *binance.Client
    Api           exchanges.Api
}

func (v *KrakenApi) GetBalance() []exchanges.Balance {
    // Requires v.client
    return []exchanges.Balance{}
}

In main.go

var exchange *Api

Now my thought was I should be able to call something like exchange.GetBalance() and it would use the GetBalance function from above. I would also need some kind of casting? I'm quite lost here. The exchange could either be Binance or Kraken--that gets decided at runtime. Some other code basically calls a GetExchange function which returns an instance of the required API object (already casted in either BinanceApi/KrakenApi)

I'm aware inheritance and polymorphism don't work like other languages, hence my utter confusion. I'm struggling to know what needs to go where here. Go seems to require loads of annoying code necessary for what other languages do on the fly

  • Related