Answer the question
In order to leave comments, you need to log in
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()
}
Answer the question
In order to leave comments, you need to log in
// Вводим интерфейс с методом 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 questionAsk a Question
731 491 924 answers to any question