Golang return nil - go

I am trying to wrap my head around Golang's types and interfaces but am struggling a bit to do so. Anyways, a common pattern that I see is func Whatever() (thing string, err error). I get how all of that works, but the one thing I am confused on is why it is ok to return "thing", nil. The specific instance that I am looking at is in revel here-
func (c *GorpController) Begin() revel.Result {
txn, err := Dbm.Begin()
if err != nil {
panic(err)
}
c.Txn = txn
return nil
}
revel.Result is an interface with this signature-
type Result interface {
Apply(req *Request, resp *Response)
}
Anyways, I am just curious how returning nil satisfies the compiler in that occasion. Is there a resource that I can be pointed to for that?

This is similar to returning a nil error: see "Why is my nil error value not equal to nil? "
Under the covers, interfaces are implemented as two elements, a type and a value.
The value, called the interface's dynamic value, is an arbitrary concrete value and the type is that of the value. For the int value 3, an interface value contains, schematically, (int, 3).
An interface value is nil only if the inner value and type are both unset, (nil, nil). In particular, a nil interface will always hold a nil type.
If we store a pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (*int, nil).
Such an interface value will therefore be non-nil even when the pointer inside is nil.
Here nil is the zero-value of the interface revel.Result.

Related

Nil pointer confusion [duplicate]

I fail to understand how to correctly assure that something is not nil in this case:
package main
type shower interface {
getWater() []shower
}
type display struct {
SubDisplay *display
}
func (d display) getWater() []shower {
return []shower{display{}, d.SubDisplay}
}
func main() {
// SubDisplay will be initialized with null
s := display{}
// water := []shower{nil}
water := s.getWater()
for _, x := range water {
if x == nil {
panic("everything ok, nil found")
}
// First iteration display{} is not nil and will
// therefore work, on the second iteration
// x is nil, and getWater panics.
x.getWater()
}
}
The only way I found to check if that value is actually nil is by using reflection.
Is this really wanted behaviour? Or do I fail to see some major mistake in my code?
Play link here
The problem here is that shower is an interface type. Interface types in Go hold the actual value and its dynamic type. More details about this: The Laws of Reflection #The representation of an interface.
The slice you return contains 2 non-nil values. The 2nd value is an interface value, a (value;type) pair holding a nil pointer value and a *display concrete type. Quoting from the Go Language Specification: Comparison operators:
Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.
So if you compare it to nil, it will be false. If you compare it to an interface value representing the pair (nil;*display), it will be true:
if x == (*display)(nil) {
panic("everything ok, nil found")
}
This seems unfeasible as you'd have to know the actual type the interface holds. But note that you can use reflection to tell if a non-nil interface value wraps a nil value using Value.IsNil(). You can see an example of this on the Go Playground.
Why is it implemented this way?
Interfaces unlike other concrete types (non-interfaces) can hold values of different concrete types (different static types). The runtime needs to know the dynamic or runtime-type of the value stored in a variable of interface type.
An interface is just a method set, any type implements it if the same methods are part of the method set of the type. There are types which cannot be nil, for example a struct or a custom type with int as its underlying type. In these cases you would not need to be able to store a nil value of that specific type.
But any type also includes concrete types where nil is a valid value (e.g. slices, maps, channels, all pointer types), so in order to store the value at runtime that satisfies the interface it is reasonable to support storing nil inside the interface. But besides the nil inside the interface we must store its dynamic type as the nil value does not carry such information. The alternate option would be to use nil as the interface value itself when the value to be stored in it is nil, but this solution is insufficient as it would lose the dynamic type information.
Some people say that Go's interfaces are dynamically typed, but that is misleading. They are statically typed: a variable of interface type always has the same static type, and even though at run time the value stored in the interface variable may change type, that value will always satisfy the interface.
In general if you want to indicate nil for a value of interface type, use explicit nil value and then you can test for nil equality. The most common example is the built-in error type which is an interface with one method. Whenever there is no error, you explicitly set or return the value nil and not the value of some concrete (non-interface) type error variable (which would be really bad practice, see demonstration below).
In your example the confusion arises from the facts that:
you want to have a value as an interface type (shower)
but the value you want to store in the slice is not of type shower but a concrete type
So when you put a *display type into the shower slice, an interface value will be created, which is a pair of (value;type) where value is nil and type is *display. The value inside the pair will be nil, not the interface value itself. If you would put a nil value into the slice, then the interface value itself would be nil and a condition x == nil would be true.
Demonstration
See this example: Playground
type MyErr string
func (m MyErr) Error() string {
return "big fail"
}
func doSomething(i int) error {
switch i {
default:
return nil // == nil
case 1:
var p *MyErr
return p // != nil
case 2:
return (*MyErr)(nil) // != nil
case 3:
var p *MyErr
return error(p) // != nil because the interface points to a
// nil item but is not nil itself.
case 4:
var err error // == nil: zero value is nil for the interface
return err // This will be true because err is already interface type
}
}
func main() {
for i := 0; i <= 4; i++ {
err := doSomething(i)
fmt.Println(i, err, err == nil)
}
}
Output:
0 <nil> true
1 <nil> false
2 <nil> false
3 <nil> false
4 <nil> true
In case 2 a nil pointer is returned but first it is converted to an interface type (error) so an interface value is created which holds a nil value and the type *MyErr, so the interface value is not nil.
Let's think of an interface as a pointer.
Say you have a pointer a and it's nil, pointing to nothing.
var a *int // nil
Then you have a pointer b and it's pointing to a.
var b **int
b = &a // not nil
See what happened? b points to a pointer that points to nothing. So even if it's a nil pointer at the end of the chain, b does point to something - it isn't nil.
If you'd peek at the process' memory, it might look like this:
address | name | value
1000000 | a | 0
2000000 | b | 1000000
See? a is pointing to address 0 (which means it's nil), and b is pointing to the address of a (1000000).
The same applies to interfaces (except that they look a bit different in memory).
Like a pointer, an interface pointing to a nil pointer would not be nil itself.
Here, see for yourself how this works with pointers and how it works with interfaces.
I'll take an alternative route to answer your concrete question, by providing the exact answer you were looking for:
Replace the check:
if x == nil {
panic("everything is ok. nil found")
}
with:
if _, ok := x.(display); !ok {
panic("everything is ok. nil found")
}
The idea here is that we are trying to convert the interface type (shower) to the concrete type display. Obviously the second slice item (d.SubDisplay) is not.

how to append nil to dynamic type slice by reflect.Append

Code below will raise a runtime error when append reflect.Value of nil:
package main
import (
"fmt"
"reflect"
)
func main() {
var list []interface{}
v := reflect.ValueOf(list)
v = reflect.Append(v, reflect.ValueOf(1)) // [1]
v = reflect.Append(v, reflect.ValueOf("1")) // [1, 1]
v = reflect.Append(v, reflect.ValueOf(nil)) // runtime error
fmt.Println(v)
}
So
why there is a runtime error?
how can I use reflect.Append to add a nil to interface{} slice?
interface{} is an interface type, and they are "tricky". They are wrappers around a concrete value and the concrete type, schematically a (value, type) pair.
So when you pass a concrete value to a function that expects an interface{} value, the concrete value will be wrapped in an interface{} value automatically, implicitly. If you pass a nil to such a function, the interface value itself will be nil. If you pass a nil pointer to it, such as (*int)(nil), the interface value will not be nil but an interface value holding "(nil, *int)".
If you pass nil to reflect.ValueOf(), it results in a "zero" reflect.Value which represents no value at all. If you pass this to reflect.Append(), it will not have the type information, it will not know what you want to append to the slice.
It is possible to create a value that represents the nil interface value.
To do that, we may start from the type descriptor of a value of an interface pointer (pointers to interface rarely makes sense, but this is one of them). We navigate to the type descriptor of the pointed type, which is interface{}. We obtain a zero value of this type (using reflect.Zero()), which is nil (zero value of interface types is nil).
Zero returns a Value representing the zero value for the specified type. The result is different from the zero value of the Value struct, which represents no value at all.
So this is how it looks like:
typeOfEmptyIface := reflect.TypeOf((*interface{})(nil)).Elem()
valueOfZeroEmptyIface := reflect.Zero(typeOfEmptyIface)
v = reflect.Append(v, valueOfZeroEmptyIface)
Or as a single line:
v = reflect.Append(v, reflect.Zero(reflect.TypeOf((*interface{})(nil)).Elem()))
To check the results, let's use:
fmt.Printf("%#v\n", v)
And also let's type-assert back the slice, and add a nil value using the builtin append() function:
list = v.Interface().([]interface{})
list = append(list, nil)
fmt.Printf("%#v\n", list)
Let's do an explicit, extra check if the elements are nil (compare them to nil). Although using %#v verb this is redundant, %v likes to print non-nil interfaces holding nil concrete values just as nil (the same as if the interface value itself would be nil).
fmt.Println(list[2] == nil, list[3] == nil)
Ouptut will be (try it on the Go Playground):
[]interface {}{1, "1", interface {}(nil)}
[]interface {}{1, "1", interface {}(nil), interface {}(nil)}
true true
See related question: Hiding nil values, understanding why golang fails here
Also: The Go Blog: The Laws of Reflection

Different result on comparing errors to nil [duplicate]

I fail to understand how to correctly assure that something is not nil in this case:
package main
type shower interface {
getWater() []shower
}
type display struct {
SubDisplay *display
}
func (d display) getWater() []shower {
return []shower{display{}, d.SubDisplay}
}
func main() {
// SubDisplay will be initialized with null
s := display{}
// water := []shower{nil}
water := s.getWater()
for _, x := range water {
if x == nil {
panic("everything ok, nil found")
}
// First iteration display{} is not nil and will
// therefore work, on the second iteration
// x is nil, and getWater panics.
x.getWater()
}
}
The only way I found to check if that value is actually nil is by using reflection.
Is this really wanted behaviour? Or do I fail to see some major mistake in my code?
Play link here
The problem here is that shower is an interface type. Interface types in Go hold the actual value and its dynamic type. More details about this: The Laws of Reflection #The representation of an interface.
The slice you return contains 2 non-nil values. The 2nd value is an interface value, a (value;type) pair holding a nil pointer value and a *display concrete type. Quoting from the Go Language Specification: Comparison operators:
Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.
So if you compare it to nil, it will be false. If you compare it to an interface value representing the pair (nil;*display), it will be true:
if x == (*display)(nil) {
panic("everything ok, nil found")
}
This seems unfeasible as you'd have to know the actual type the interface holds. But note that you can use reflection to tell if a non-nil interface value wraps a nil value using Value.IsNil(). You can see an example of this on the Go Playground.
Why is it implemented this way?
Interfaces unlike other concrete types (non-interfaces) can hold values of different concrete types (different static types). The runtime needs to know the dynamic or runtime-type of the value stored in a variable of interface type.
An interface is just a method set, any type implements it if the same methods are part of the method set of the type. There are types which cannot be nil, for example a struct or a custom type with int as its underlying type. In these cases you would not need to be able to store a nil value of that specific type.
But any type also includes concrete types where nil is a valid value (e.g. slices, maps, channels, all pointer types), so in order to store the value at runtime that satisfies the interface it is reasonable to support storing nil inside the interface. But besides the nil inside the interface we must store its dynamic type as the nil value does not carry such information. The alternate option would be to use nil as the interface value itself when the value to be stored in it is nil, but this solution is insufficient as it would lose the dynamic type information.
Some people say that Go's interfaces are dynamically typed, but that is misleading. They are statically typed: a variable of interface type always has the same static type, and even though at run time the value stored in the interface variable may change type, that value will always satisfy the interface.
In general if you want to indicate nil for a value of interface type, use explicit nil value and then you can test for nil equality. The most common example is the built-in error type which is an interface with one method. Whenever there is no error, you explicitly set or return the value nil and not the value of some concrete (non-interface) type error variable (which would be really bad practice, see demonstration below).
In your example the confusion arises from the facts that:
you want to have a value as an interface type (shower)
but the value you want to store in the slice is not of type shower but a concrete type
So when you put a *display type into the shower slice, an interface value will be created, which is a pair of (value;type) where value is nil and type is *display. The value inside the pair will be nil, not the interface value itself. If you would put a nil value into the slice, then the interface value itself would be nil and a condition x == nil would be true.
Demonstration
See this example: Playground
type MyErr string
func (m MyErr) Error() string {
return "big fail"
}
func doSomething(i int) error {
switch i {
default:
return nil // == nil
case 1:
var p *MyErr
return p // != nil
case 2:
return (*MyErr)(nil) // != nil
case 3:
var p *MyErr
return error(p) // != nil because the interface points to a
// nil item but is not nil itself.
case 4:
var err error // == nil: zero value is nil for the interface
return err // This will be true because err is already interface type
}
}
func main() {
for i := 0; i <= 4; i++ {
err := doSomething(i)
fmt.Println(i, err, err == nil)
}
}
Output:
0 <nil> true
1 <nil> false
2 <nil> false
3 <nil> false
4 <nil> true
In case 2 a nil pointer is returned but first it is converted to an interface type (error) so an interface value is created which holds a nil value and the type *MyErr, so the interface value is not nil.
Let's think of an interface as a pointer.
Say you have a pointer a and it's nil, pointing to nothing.
var a *int // nil
Then you have a pointer b and it's pointing to a.
var b **int
b = &a // not nil
See what happened? b points to a pointer that points to nothing. So even if it's a nil pointer at the end of the chain, b does point to something - it isn't nil.
If you'd peek at the process' memory, it might look like this:
address | name | value
1000000 | a | 0
2000000 | b | 1000000
See? a is pointing to address 0 (which means it's nil), and b is pointing to the address of a (1000000).
The same applies to interfaces (except that they look a bit different in memory).
Like a pointer, an interface pointing to a nil pointer would not be nil itself.
Here, see for yourself how this works with pointers and how it works with interfaces.
I'll take an alternative route to answer your concrete question, by providing the exact answer you were looking for:
Replace the check:
if x == nil {
panic("everything is ok. nil found")
}
with:
if _, ok := x.(display); !ok {
panic("everything is ok. nil found")
}
The idea here is that we are trying to convert the interface type (shower) to the concrete type display. Obviously the second slice item (d.SubDisplay) is not.

What does nil mean in golang?

There are many cases using nil in golang. For example:
func (u *URL) Parse(ref string) (*URL, error) {
refurl, err := Parse(ref)
if err != nil {
return nil, err
}
return u.ResolveReference(refurl), nil
}
but we can't use it like this:
var str string //or var str int
str = nil
the golang compiler will throw a can't use nil as type string in assignment error.
Looks like nil can only be used for a pointer of struct and interface. If that is the case, then what does it mean?
and when we use it to compare to the other object, how do they compare, in other words, how does golang determine one object is nil?
EDIT:For example, if an interface is nil, its type and value must be nil at the same time. How does golang do this?
In Go, nil is the zero value for pointers, interfaces, maps, slices, channels and function types, representing an uninitialized value.
nil doesn't mean some "undefined" state, it's a proper value in itself. An object in Go is nil simply if and only if it's value is nil, which it can only be if it's of one of the aforementioned types.
An error is an interface, so nil is a valid value for one, unlike for a string. For obvious reasons a nil error represents no error.
nil in Go is simply the NULL pointer value of other languages.
You can effectively use it in place of any pointer or interface (interfaces are somewhat pointers).
You can use it as an error, because the error type is an interface.
You can't use it as a string because in Go, a string is a value.
nil is untyped in Go, meaning you can't do that:
var n = nil
Because here you lack a type for n. However, you can do
var n *Foo = nil
Note that nil being the zero value of pointers and interfaces, uninitialized pointers and interfaces will be nil.
nil is also a value but only difference is- it is empty.
In Javascript for the un-initialized variable will be undefined. In the same way Golang has nil as default value for all the un-initalized data types.
nil in Go means a zero value for pointers, interfaces, maps, slices, and channels.
It means the value is uninitialized
For the data types like slice and pointers which "refer" to other types, "nil" indicates that the variable does not refer to an instance (equivalent of null pointer in other languages)
It is thee zero value of the variables of type functions, maps, interfaces, channels and structures
nil is a predeclared identifier in Go that represents zero values for pointers, interfaces, channels, maps, slices and function types.
nil being the zero value of pointers and interfaces, uninitialized pointers and interfaces will be nil.
In Go, string can’t be nil. A string doesn’t qualify to be assigned nil.
a := nil // It will throw an error 'use of untyped nil'
var a *int = nil //It will work
In Go nil is predeclared identifier that represents nothing for pointers, interfaces, channels, maps, slices and function types. Uninitialized pointers and interfaces will be nil. A string doesn’t qualify to be either of the above-mentioned types and hence can’t be assigned nil.
If you declare a variable by shorthand decleration like this: variable:=nil this will give compile time error because compiler has no idea which type it has to assign to variable .
In Go map, slice and function doesn't support comparison but can be compared with nil.
If any two map, slice or function are assigned to nil and compared with each other then it will raise runtime error.
But if we assign nil to any two pointer variables and compare them with each other then no error will occur.
package main
import (
"fmt"
)
func main() {
var i *int =nil
var j *int =nil
if i==j {
fmt.Println("equal")
} else {
fmt.Println("no")
}
}
This code works fine and prints output as equal.
In Golang, datatype can use nil is pointers, interfaces, maps, slices, channels, function types and errors
in String value is ""
in INT value is ZERO
In Golang, zero value is the default value for defined variables. The default value of different datatypes are:
0 for integer types
0.0 for floating types
false for boolean types
"" for string types
nil for interfaces, slices, channels, maps, pointers and functions
So, nil is the zero value or default value for interfaces, slices, channels, maps, pointers and functions.
For example,
var a int
var s []int
var s1 []int = []int{1, 2}
fmt.Println(a == nil) // throw error
// invalid operation: a == nil (mismatched types int and untyped nil)
fmt.Println(s == nil) // true
fmt.Println(s1 == nil) // false
Since error is an interface, we can write
_, err := Parse("")
if err != nil { // if there is an error
// handle error
}

This nil instance of a struct, that satisfies the error interface, is not showing as nil

This should be a gimme for someone. Why do I not get what I expect ("Error is not nil") here?
http://play.golang.org/p/s8CWQxobVL
type Goof struct {}
func (goof *Goof) Error() string {
return fmt.Sprintf("I'm a goof")
}
func TestError(err error) {
if err == nil {
fmt.Println("Error is nil")
} else {
fmt.Println("Error is not nil")
}
}
func main() {
var g *Goof // nil
TestError(g) // expect "Error is nil"
}
This is, it turns out, a Frequently Asked Question about Go, and the short answer is that interface comparisons compare the type and the value, and (*Goof)(nil) and error(nil) have different types.
Since if err != nil is standard, you want a return value that'll work with it. You could declare var err error instead of var g *Goof: err's zero value is conveniently error(nil)
Or, if your func returns an error, return nil will return what you want.
For more background, here's the start of the FAQ's answer:
Under the covers, interfaces are implemented as two elements, a type and a value. The value, called the interface's dynamic value, is an arbitrary concrete value and the type is that of the value. For the int value 3, an interface value contains, schematically, (int, 3).
An interface value is nil only if the inner value and type are both unset, (nil, nil). In particular, a nil interface will always hold a nil type. If we store a pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (*int, nil). Such an interface value will therefore be non-nil even when the pointer inside is nil.
And == is strictly checking if the types are identical, not if a type (*Goof) implements an interface (error). Check out the original for more.
If it helps clarify, this doesn't only happen with nil: in this example, the data underlying the x and y variables is obviously 3, but they have different types. When you put x and y into interface{}s, they compare as unequal:
package main
import "fmt"
type Bob int
func main() {
var x int = 3
var y Bob = 3
var ix, iy interface{} = x, y
fmt.Println(ix == iy)
}

Resources