S
S
Sergey Romanov2020-04-02 17:24:26
go
Sergey Romanov, 2020-04-02 17:24:26

How to find out if a struct variable has a method?

I have a program. Here is a small piece of code.

type ModbusTCP struct {
  Device Device
  Client modbus.Client
  Handler *modbus.TCPClientHandler 
}

// Connect connect to the device
func (m *ModbusTCP) Connect(d Device) (err error) {
  m.Device = d

  cs := d.DParams.(map[string]interface{})["ip"].(string) +
    ":" + fmt.Sprintf("%.0f", d.DParams.(map[string]interface{})["port"].(float64))
  
  handler := modbus.NewTCPClientHandler(cs)
  handler.Timeout = 10 * time.Second
  handler.SlaveId = 0xFF

  err = handler.Connect()
  if err != nil {
    return errors.New("Fail to connect (" + cs + ") " + err.Error())
  }

  m.Handler = handler
  return nil
}

// End connect to the device
func (m *ModbusTCP) End() {
  LogDev("End connection", logrus.Fields{"id": m.Device.ID})
  m.Handler.Close()
}


This is the preparation of connection to the device via Modbus. So everything works, I open and close the connection as needed. But there is such a situation that I can call End () and m.Handler is already empty by that time.

How can I check if there is such a .Close() method on the handler before calling it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2020-04-02
@pav5000

// Вводим интерфейс с методом Close
// Можем даже использовать готовый io.Closer
type Closer interface {
    Close()
}

// Проверяем, удовлетворяет ли Handler интерфейсу
if casted,ok := m.Handler.(Closer); ok {
    // Если удовлетворяет, вызываем метод
    casted.Close()
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question