下面是一个结构Config
,它包含一个返回ReturnNewAddress
接口的匿名函数net.Conn
。然后使用ReturnNewAddress
返回'addr'。
type struct Config {
ReturnNewAddress func(net.Conn, error)
}
稍后在下面调用匿名函数ReturnnewAddress
时,请注意cfg
是Config
的实例。
addr, err := cfg.ReturnNewAddress()
所以我的问题是 - 接口net.Conn
如何知道使用什么功能,因为接口具有许多不同的功能?让我感到困惑的是LocalAddr()
或RemoteAddr()
没有被隐含地调用。如何明确使用这些方法之一。如果我需要LocalAddr
明确使用RemoteAddr
,该怎么办?
以下是net.Conn的go doc:
type Conn interface {
// Read reads data from the connection.
// Read can be made to time out and return an Error with Timeout() == true
// after a fixed time limit; see SetDeadline and SetReadDeadline.
Read(b []byte) (n int, err error)
// Write writes data to the connection.
// Write can be made to time out and return an Error with Timeout() == true
// after a fixed time limit; see SetDeadline and SetWriteDeadline.
Write(b []byte) (n int, err error)
// Close closes the connection.
// Any blocked Read or Write operations will be unblocked and return errors.
Close() error
// LocalAddr returns the local network address.
LocalAddr() Addr
// RemoteAddr returns the remote network address.
RemoteAddr() Addr
// SetDeadline sets the read and write deadlines associated
// with the connection. It is equivalent to calling both
// SetReadDeadline and SetWriteDeadline.
//
// A deadline is an absolute time after which I/O operations
// fail with a timeout (see type Error) instead of
// blocking. The deadline applies to all future and pending
// I/O, not just the immediately following call to Read or
// Write. After a deadline has been exceeded, the connection
// can be refreshed by setting a deadline in the future.
//
// An idle timeout can be implemented by repeatedly extending
// the deadline after successful Read or Write calls.
//
// A zero value for t means I/O operations will not time out.
SetDeadline(t time.Time) error
// SetReadDeadline sets the deadline for future Read calls
// and any currently-blocked Read call.
// A zero value for t means Read will not time out.
SetReadDeadline(t time.Time) error
// SetWriteDeadline sets the deadline for future Write calls
// and any currently-blocked Write call.
// Even if write times out, it may return n > 0, indicating that
// some of the data was successfully written.
// A zero value for t means Write will not time out.
SetWriteDeadline(t time.Time) error
}
Conn is a generic stream-oriented network connection.
答案 0 :(得分:2)
问题不完全清楚,但是......
看起来Config类型的代码有一个拼写错误
ReturnNewAddress func(net.Conn, error)
没有与后面的代码兼容的函数类型
addr, err := cfg.ReturnNewAddress()
我认为配置结构类型应该定义为
type struct Config {
ReturnNewAddress func()(net.Conn, error)
}
基于此,从addr
调用返回的变量cfg.ReturnNewAddress()
具有类型net.Conn
- 因此它是实现接口net.Conn
的值。因此,您可以按如下方式显式调用所需的函数:
localAddr :=addr.LocalAddr();
remoteAddr := addr.RemoteAddr();