指针对象,如果不是指针对象,那么方法必须是非指针方法

package main

import (
	"Wsd"
	"fmt"
	"time"
)

const (
	tcpHeaderSize = 7
	tcpMaxLength  = 260
	// Default TCP timeout is not set
	tcpTimeout     = 10 * time.Second
	tcpIdleTimeout = 60 * time.Second
)

type ClientHandlert interface {
	Packager1
	Transporter1
}
type Test struct {

}

func (t *Test)Verify(aduRequest []byte, aduResponse []byte) (err error) {

	return err
}
func (t Test)Send1(aduRequest []byte) (aduResponse []byte, err error) {
	return
}

func main() {
	handler := Wsd.NewTCPClientHandler("localhost:502")
	fmt.Printf("%T\n", handler)
	fmt.Printf("%+v\n", handler)
	//&{tcpPackager:{transactionId:0 SlaveId:0} tcpTransporter:{Address:localhost:502 Timeout:10s IdleTimeout:1m0s Logger:<nil> mu:{state:0 sema:0} conn:<nil> closeTimer:<nil> lastActivity:{wall:0 ext:0 loc:<nil>}}}
	//NewClient(handler)
	test(handler)
	var a *Test/*必须是指针对象,如果不是指针对象,那么方法必须是非指针方法*/
	test(a)//对象赋值给接口
}

func test(ss ClientHandlert) {
	/*ss 此时是ClientHandler的一个变量,一旦由外部对象调用,则变成了对象*/
fmt.Printf("%T\n",ss)
}
// NewClient creates Ainterface new modbus client with given backend handler.
func NewClient(handler ClientHandlert) Client { /*对象赋值给接口*/
	return &client{packager: handler, transporter: handler} /*返回该接口对象*/
}

type Packager1 interface {
	//Encode(pdu *ProtocolDataUnit) (adu []byte, err error)
	//Decode(adu []byte) (pdu *ProtocolDataUnit, err error)
	Verify(aduRequest []byte, aduResponse []byte) (err error)
}

// Transporter specifies the transport layer.
type Transporter1 interface {
	Send1(aduRequest []byte) (aduResponse []byte, err error)
}

type client struct {
	packager    Packager1 //接口作为结构体参数
	transporter Transporter1
}

type ProtocolDataUnit struct {
	FunctionCode byte
	Data         []byte
}

type Client interface {
}

func (mb *tcpPackager) Encode(pdu *ProtocolDataUnit) (adu []byte, err error) {

	return
}

type tcpPackager struct {
	// For synchronization between messages of server & client
	transactionId uint32 /*用于服务器和客户端消息之间的同步*/
	// Broadcast address is 0
	SlaveId byte /*??0为广播*/
}

对象赋值给接口必须要注意的地方

或者这样

var a Test/*必须是指针对象,如果不是指针对象,那么方法必须是非指针方法*/
	test(&a)//对象赋值给接口

只要有一个方法是指针对象方法,就必须是传递指针对象

猜你喜欢

转载自blog.csdn.net/weixin_42544051/article/details/85261921