net.go ok function's c != nil check right ?

57 views
Skip to first unread message

apma...@gmail.com

unread,
Jun 3, 2020, 3:04:16 AM6/3/20
to golang-nuts
Read function at net.go is like this:

func (c *conn) Read(b []byte) (int, error) {
    if !c.ok() {

the ok checks that c is non nil:
func (c *conn) ok() bool { return c != nil && c.fd != nil }

how can c ever be nil ? if it would c.ok() call would crash.

Gregor Best

unread,
Jun 3, 2020, 3:11:43 AM6/3/20
to golan...@googlegroups.com

Methods are part of the type, not of the value. It is perfectly safe to call methods on a nil value.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4969df86-c3ec-4b3f-916d-35a986884362%40googlegroups.com.
-- 
--
  Gregor Best
  be...@pferdewetten.de

Dan Kortschak

unread,
Jun 3, 2020, 3:21:24 AM6/3/20
to golan...@googlegroups.com
It's perfectly valid to call a method on a nil receiver, so long at the
nil receiver is not dereferenced.

https://play.golang.org/p/Z-zXlj0-eVy

apma...@gmail.com

unread,
Jun 3, 2020, 3:38:31 AM6/3/20
to golang-nuts
ooh.. thanks.
Reply all
Reply to author
Forward
0 new messages