Nil inconsistency? solved (kind of)

Hi.

I have this code:

var x *t =   &         .... some more code
fmt.Printf("%v, %v\n", x, x == nil)

And it prints this:

<nil>, false

I should extract the problem from the whole thing, but it’s quite large. It’s a pointer, it’s probably nil because it also raises an exception if dereferenced. But I can’t check for nil and get true. In which case would this happen?

Sorry, got it. Had gcflacs set to -B and got the pointer from a bad place.

Still, I wish it had told me some more “truth”. :wink:

I though because you are assigning & as value to your variable. (will always not nil)

If you want to assigning your var with nil, just throw the nil when assigning it. (or return the nil)

package main

import "fmt"

type t string

func main() {
	var x *t
	fmt.Printf("%v, %v\n", x, x == nil)

	var y t = ""
	x = &y
	fmt.Printf("%v, %v\n", x, x == nil)
}

output:

<nil>, true
0xc000014250, false

Go Playground: Go Playground - The Go Programming Language

@noo How you can get <nil>, false ? What value you are assigned?

What you say sounds very right to me, & should never give me nil. So actually I was really not giving it attention.

The compiler/runtime said it’s nil because the code is &something.anotherthing[out_of_bounds_index]. It should have said “0x23456789 which is an invalid pointer”, but instead it just called it " < nil > ", which is wrong.

I assume that when compiling with “-gcflags -B” for turning off the bounds checking, Golang will send me into unsafe land and it’s all my fault, even if the runtime is technically not correct when it says “< nil >”. It should say " < inaccessible > " in order to not confuse me, but now I know anyway.

PS: len(something.anotherthing) is zero, so index 0 is already out of bounds. Maybe that also plays a role. I have no tried to reproduce anything in playground because I don’t know whether/how it accepts compiler switches.

PS2: It happens on Windows.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.