by nemothekid · 5y ago · 0 comments
package main
type Compressor interface {
compress() []byte
}
type GZipComprosser struct {
internal byte
}
func (c *GZipComprosser) compress() []byte {
return []byte{c.internal}
}
func DoCompress(c Compressor) []byte {
if c == nil {
return []byte{}
}
return c.compress()
}
func main() {
var c *GZipComprosser
c = nil
DoCompress(c)
}
This is the "nil interface" trap and will crash with an NPE even though are "checking" nil. func returnsNilError() (int, *MyErr) {
return 0, nil
}
// case 1: no other use of error, nil works
{
i, err := returnsNilError()
_ = i
fmt.Printf("err is nil: %v\n", err == nil)
}
// case 2: someone adds a couple lines of code before that call...
{
_, err := os.Open("/tmp/file")
i, err := returnsNilError()
_ = i
fmt.Printf("err is nil: %v\n", err == nil)
}
// Wait, what? Someone adding a line of code before your code changes how your nil check works?
Playground: https://play.golang.org/p/-t1Hq8WMF8lThis, I think, is the reason everyone uses "error" in their return values in go, even though using a specific type (like "*os.PathError") would make it much easier to know what possible error conditions a function could have.
Thanks!
Another way to explain the difference is the following:
// case 1 is the same as
var i int
// inferred type of *MyErr because that's what returnsNilError returns
var err *MyErr
i, err = 0, (*MyErr)(nil)
// err is of type (nil)(*MyErr)
// case 2 is the same as
// inferred type of error because os.Open returns that
var err error
err = os.Open("/tmp/file")
var i int
i err = 0, (error)((*MyErr)(nil))
// err is of type (error)((*MyErr)(nil))
Note well that "err" is a different type in those two cases. Type inference, plus the fact that short variable decleration re-uses an existing variable if the type is compatible, can result in previous code changing what type a variable is.It's well known that an interface with a type is != nil (i.e. "var nilErr *MyErr = nil; var errIface error = nilErr" results in an 'errIface' that is not equal to an untyped nil).
I hope that explanation made sense to you.
It is not possible to always do this; `if val, err := ...; err != nil { } else { use(val) }` is a Bit Much.
The second := in case 2 should have raised a visual alarm. The fact that := even assigned for err a second time means inference could have happened, like
err = (*MyErr)(nil)
To catch this, you could have written the nil check like: fmt.Printf("err is nil: %v\n", (*MyErr)(err) == nil)
and the compiler will croak. Or, to prevent this, replicate the inference explicitly: fmt.Printf("err is nil: %v\n", err == (*MyErr)(nil))I hypothesize, but can not prove, that the root problem isn't that there are two nils. The root problem is that people incorrectly think nil is always invalid. It is not. This is perfectly legal (https://play.golang.org/p/71BNAyXIzRv )
type Thing string
func (t *Thing) DoSomething() {
if t == nil {
fmt.Println("nil thing")
return
}
fmt.Println(string(*t))
}
Nil pointers are perfectly legal values. You can call methods on them no problem. I have places where I use them; for instance, I have a memory pooling implementation where the nil pointer simply fills requests via "make" directly and does no pooling, so you can swap it out easily to test if it is causing some other bug.So I think people think of there as being "two equally invalid values", but it's not true. There's the nil interface, which is pretty useless, but an interface containing a nil pointer in it is legal and may very well completely successfully implement the interface. Checking to see whether the interface "contains" a nil pointer is almost always an error. It is not something you should ever do when you have an interface value.
The real error occurs when you put the nil pointer in an interface value that can't correctly implement the interface, which is also nothing particularly special; putting anything in an interface value that can't implement the interface is an Already Lost situation. That the error then propagates around is bad, but the error occurred earlier and it's already too late to fix it by the time some other bit of code receives this broken value. Good code never has any reason to penetrate the interface and interrogate the underlying type for whether or not it is nil; if you are routinely encountering this problem, if you stop putting invalid implementations in an interface value, the problem will go away. I use all these features routinely and don't encounter this problem, because I know to never lie by putting something in an interface value that doesn't implement the interface.
So here's where I do that:
https://github.com/gwd/session-scheduler/blob/master/handle_...
The pattern is basically:
var foo = interface{}
switch (something) {
case A:
foo = Foo()
case B:
foo = Bar()
}
Foo and Bar both return different concrete types which are nil if the request can't be handled. I want to do something if either Foo or Bar return 'nil', and also if neither case A nor case B are taken. So I've got: if foo == nil || reflect.ValueOf(foo)IsNil() {
// handle the error
}
// Pass foo elsewhere
I mean yeah, I certainly could arrange things differently; but in general I think that's not an unreasonable thing to expect to be able to do.> The real error occurs when you put the nil pointer in an interface value that can't correctly implement the interface... putting anything in an interface value that can't implement the interface is an Already Lost situation.
First of all, that's not the case in my example above: nil can satisfy every method of `interface{}`.
Secondly, my compiler refuses to compile if I assign something other than a nil pointer that can't implement the interface. If putting nil into an interface is such a bad idea, the compiler should prevent you from doing it.
As it turns out, a lot of the improvements they were thinking about could be done without breaking backwards compatibility; which of course has some huge advantages.
Out of curiosity, what are the first two?
For me it's:
1. context.Context and putting everything under the sun there, untyped (which is a design fault, not just "people using it wrong")
2. reusing the looping variable in for loop
2.5. general awkwardness of go templating (I plan to write whole article about this, but too lazy to actually write it)
The language makes a big deal about memory management and data structure ownership, and as a result it’s sorta a pain to send stuff around on the stack, both at initialization and runtime. As a casual golang user, the context mess feels like an escape hatch to help with those problems. I’d prefer some GC compromises built into the language itself instead.
FWIW, I think request-scoped globals are terrible and is among the many things I hated about Flask. I think generics will largely solve this problem by allowing us to write generic middleware with a type-safe context and probably even functions to compose the middleware and automatically propagate the context variables.
What (I think) you are suggesting implies globally scoped, mutable variables that affect control flow dramatically. Sounds really hard to reason about and very munch anti-Go-explicitness. Context is the handle by which an outer context holds on to the nested ones.
The only non-bonkers way to have a handle like that would be to give every function a getContext function to query some kind of context tree and signal parent/children. This is totally against Go explicitness as well.
Maybe something like Scala's implicits to sugar it, but that's another not-go-looking pattern (although it would be nice)
It makes me want to port it to Rust, since so many of the major Rust templating libraries are Jinja copies or Handlebars copies.
Go authors themselves admit it might have been a design mistake, but is unfixable without breaking compatibility.
https://golang.org/doc/faq#closures_and_goroutines
> This behavior of the language, not defining a new variable for each iteration, may have been a mistake in retrospect. It may be addressed in a later version but, for compatibility, cannot change in Go version 1.
1. Error handling. Not only is `if err == nil` (or my preferred `if _, err := foo(); err == nil`) a lot of noise, errors are completely opaque and might as well be strings.
2. Dependency management. It was a mess for a long time, go modules fixed a lot of issues in it's own way but still has problems (e.g. the "v2" workaround). My theory is they expected everyone, in some way, to "self-host" their modules (like how Java would have com.google.foo.bar, eventually everyone else would have "http://go.company/package", but GitHub became central repository of software for everyone and linking directly to packages was no longer sound).
Errors in modern Go are definitely not just strings.
Before wrapped errors in Go, this would have been an easier case to make against the language.
foo := &FooError{}
if errors.As(err, &foo) {
fmt.Println("foo error!")
} func processItem(item *string) {
if item == nil {
fmt.Println("nil item")
return
}
fmt.Println(*item)
}
stuffToProcess := []string{"one", "two"}
wg := sync.WaitGroup{}
for _, item := range stuffToProcess {
wg.Add(1)
go func(s *string) {
time.Sleep(1 * time.Millisecond)
processItem(s)
wg.Done()
}(&item)
}
wg.Wait()
// What do I print?
Playground here: https://play.golang.org/p/mouvT1BkpNJ [reuse.go:26] - G601 (CWE-118): Implicit memory aliasing in for loop. (Confidence: MEDIUM, Severity: MEDIUM)
25: wg.Done()
> 26: }(&item)
27: }
[1] https://github.com/securego/gosecIt's inability to deal with cyclic references, the lack of overloading, the lack of package-level visibility and the lack of static functions all contribute to a lot of ceremony.
You end up with functions like newUserWithPassword and NewRole (casing intentional), instead of User::new() and Role::new()
You could just have a NewUser that takes a NewUserOpts which exposes a fluent interface. But again, a lot of ceremony.
You can use a package per type, but still no overloading, and you'll need a 3rd package to bridge the two if the reference each other.
After 4 years of Go, this is usually a design thing. Once I figured out how to separate and isolate domains of interest better, I stopped running into these issues entirely. My code, in and outside of Go, is much better for it. I also learned that much of "thread-safe" programming is taught this way, which makes sense.
https://play.golang.org/p/FUS2-CcHflX
The more I played with the code, the more I have to agree with the commenter. This is not obvious behavior.
You can also get into obscure behavior if your implementation does not have a pointer receiver. Take this code for example: https://play.golang.org/p/MjjGMAZL3-v How can I get a nil pointer immediately after I checked whether it was nil? This one, I do know has bitten me before. Infrequently, but it has.
func (c *GZipComprosser) compress() []byte {
if (c == nil) {
return []byte{}
}
return []byte{c.internal}
}
?I don't think that's common at all (1) nor is it a sane burden to put on developers.
(1) https://github.com/golang/go/blob/master/src/bytes/buffer.go...
1. Checking for nil receivers is rare and hardly idiomatic. (Although I have seen methods that are designed to work with nil receivers)
2. (*T)nil != nil is surprising.
A newbie looking at this code would not expect it to crash which is why I consider it a wart. In this specific case, the code was structured such that if the compressor was nil then no compression would happen. Then in some, hard to remember case, when you opted into gzip the whole thing would crash. I think I had been writing Go for about 18 months at that point and that snippet got past review. Ultimately the design had problems, (depending on `nil` to mean anything was probably dangerous and it's clearer to give NoCompression it's own type) so I'm not really arguing that the above snippet should work.
Once you understand why it's there it makes sense, but ultimately I think it's an unfortunate side effect of designing a language with nullable types.
I think newcomers are exposed to this behaviour now. For instance, it is step 12 in the tour of Go:
https://tour.golang.org/methods/12
I learnt Go before the tour was available and learnt a lot from going through the tour later on.
In Java land at some point we were taught to never use null anywhere, instead use the null object pattern.
And in Go I'd like to extend that, never call a method on a nil receiver if you can avoid it. I think it should be up to the caller to do the nil check, IF the receiver can ever be nil.
func main() {
var c Compressor // signal do nothing
DoCompress(c)
c = &GZipComprosser{} // normal call
DoCompress(c)
}