I often do nil checks on interfaces in places like constructors that may or may 
not have received optional parameters. In some cases as a parameter that may be 
nil if no implementation is required, in some cases where a functional option 
setting the interface was not given. Typically this looks something like:

func Walk(ctx context.Context, cfg Config) (chan protocol.FileInfo, error) {
w := walker{cfg}

if w.CurrentFiler == nil {
w.CurrentFiler = defaultCurrentFiler{}
}
        …
}

where the field is set to some default implementation when nil. It’s also not 
uncommon to have nil implementations of that interface, especially in tests:

type mockCurrentFiler struct{}

func (*mockCurrentFiler) CurrentFile(string) whatever {
    return nil
}

var testCurrentFiler *mockCurrentFiler // nil

…

cfg.CurrentFiler = testCurrentFiler // == nil in the new regime
Walk(ctx, cfg)

This would break, in a surprising way as the default implementation would be 
used instead of the given mock implementation. Clearly the test can be 
refactored:

cfg.CurrentFiler = &mockCurrentFiler{} // not nil

but yes, the change would break code.

I’m not saying that having this change in Go 2 would necessarily be a bad idea, 
but the current Go 1 behavior makes sense in Go 1 and there is definitely code 
that depends on it.

//jb

On 3 Nov 2017, at 11:09, oju...@gmail.com<mailto:oju...@gmail.com> wrote:

Yes, Ayan, you are quite correct. There are a lot of comparisons to check if an 
error is nil. It has it's own FAQ entry: https://golang.org/doc/faq#nil_error

Sincerely, what I am after is an example of a situation where the solution 
proposed by Dave Cheney would create a problem, like "See here. In this 
situation the proposed change would break my code."

When comparing error to nil, Dave's change would work just fine. That FAQ entry 
would not be needed anymore.

On Friday, November 3, 2017 at 7:31:47 AM UTC-2, Ayan George wrote:


On 11/03/2017 05:23 AM, oju...@gmail.com<javascript:> wrote:
> Could somebody please point me to any example of comparing an
> interface to nil, in production code? Thanks.
>

Does checking if a variable of type error is nil count?

-ayan

--
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+unsubscr...@googlegroups.com<mailto:golang-nuts+unsubscr...@googlegroups.com>.
For more options, visit https://groups.google.com/d/optout.

-- 
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+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to