为什么我不能使用 net.go 中的 conn.ok()?

Why can't I use conn.ok() from net.go?

提问人:idiocache 提问时间:12/26/2018 更新时间:12/26/2018 访问量:605

问:

我是从 Python 背景来到 Golang 的,我试图围绕各种新概念来思考。

我遇到的一件事是net.go中的这个函数:

func (c *conn) ok() bool { return c != nil && c.fd != nil }

此函数由多个 net.go 方法调用,例如 conn。读:

// Read implements the Conn Read method.
func (c *conn) Read(b []byte) (int, error) {     
if !c.ok() {        
    return 0, syscall.EINVAL
}

我正在尝试了解如何在 conn 上调用该方法,尽管这似乎不是 conn 的接口。ok()ok()

当然,我似乎无法从我的客户端代码调用:ok()

func main() {
conn, err := net.Dial("tcp", "www.reddit.com:80")
if err != nil {
    os.Exit(-1)
}
fmt.Println(&conn.ok())
}

输出:

./server.go:14:22: conn.ok undefined (type net.Conn has no field or method ok)

任何指针都值得赞赏......

评论

3赞 Peter 12/26/2018
接口名为 ,它与类型(小写)不同。Connconn

答:

2赞 Mostafa Solati 12/26/2018 #1

从 Go 文档:

可以导出标识符以允许从另一个标识符访问它 包。如果 标识符的名称是 Unicode 大写字母

因此,ok 函数不会导出,您无法在 net 包之外访问它。

2赞 Maxim 12/26/2018 #2

Go 不使用公共/私有关键字来查看标识符。如果首字母是大写字母,则标识符为 exported(public);否则不是:

  • 大写首字母:名称对包的客户端可见
  • 否则:名称(或_Name)对包的客户端不可见
0赞 cslrnr 12/26/2018 #3

net 中没有像 ok 这样的字段或方法。Conn 错误所说的是正确的。 当您尝试读取和写入 conn 时,您将获得 err 和字节数,将其读取或写入连接。