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
}
Related
I recently read on a popular programming forum that Go supports a handful of "typelesss" values — notably, nil, Go's null value/bottom type. I have fairly limited experience with Go, and one of the statements made on this forum caught me off guard — namely, that it's illegal to write x := nil in Go.
Sure enough, a toy Go program with that line doesn't compile and the compiler error clearly points out that the comment from the forum checks out: declaration and assignment of a variable to nil is disallowed. This seems like a bit of an odd limitation, but things get stranger.
It's a common idiom in Go to return partial errors by returning a tuple from a function. Something like this:
func might_error() (int, error) {
return 1, nil
}
func main() int {
x, err := might_error()
if err != nil {
panic("err was not nil!")
}
return x
}
This has at least two inconsistencies as far as I can tell:
First, even though nil is typeless on paper, it takes on the error type (by way of it implementing the Error interface combined with Go's duck typing) for the purposes of conforming to might_error's return type signature.
Second, it seems like nil is being used for that previously-illegal declaraiton-and-assignment in main, and in a situation where (at least in comparable languages) might_error could be treated as a constexpr.
Weirder still, replacing x, err := might_error() with x, err := 1, nil still errors out with use of untyped nil!
My current line of thinking is that the Error interface is injected into a specific instance of nil in cases where a function's type signature requires it, meaning that it stops being an untyped nil and becomes a typed nil for the lifetime of that specific nil instance, but I'm not at all sure that this is correct since it seems like a strange design choice by nature of it not being clearly generalizeable.
What motivated these design choices? Why have nil be untyped instead of having it be a proper null type, except when it's convenient, at which point it becomes a typed value implementing an Error interface (to the best of my understanding)?
This is a complete non-problem in the sense that in practice there can be confusion if a nil value is stored in an interface variable making that variable non-nil. This is https://golang.org/doc/faq#nil_error and everyone is bitten a few times by this problem until you learn that interface values containing a nil variable are no longer nil themself. It's a bit like with var s = []*int{nil, nil, nil} where s contains only nils but is non-nil itself.
Technically (from a language design point) you could introduce several "nils", e.g. nil for pointers, null for interfaces, noop for functions and vac for channels. (Exaggerating a bit). With this you could have:
type T whatever
func (t *T) Error() string // make *T implement error
var err error // interface variable of type error
print(err == null) // true, null is Zero-Value of interface types
print(err == nil) // COMPILER ERROR, cannot compare interface to nil (which is for pointers only
var t *T = nil // a nil pointer to T
err = t // store nil *T in err
print(err == null) // false err is no longer null, contains t
You could even remove the compiler error:
err = t // store nil *T in err
print(err == null) // false, err contains t
print(err == nil) // "deep" comparison yielding true
err = &T{} // store non-nil *T in err
print(err == null) // still false
print(err == nil) // false, value inside err is no longer nil
You also could define a default type for nil, e.g. *[]chan*func()string so that you can write x := nil like you can do with f := 3.141 where the default type of the untyped constant 3.141 is float64. But such a default type for nil would be arbitrary and not helpful at all (as my example shows; *[]chan*func()string is uncommon).
If I remember correctly there was a longer discussion about this topic on the golang-nuts mailng list where the rationals about this design was discussed. It boiled down to something like: "The actual real-life problems with having nil multiple meanings and not being a constant are tiny (basically just variants of an error type containing nil not being nil). The 'solution' to this one tiny problem would complicate the language (e.g. by introducing a null literal for the zero value of interface types) considerably. It probably is simpler to teach people that interface values containing a nil are no longer nil themself than introducing typed nils or nulls for interface types."
In more than 10 years of programming in Go I literally never had to think about a nil literal being typed or untyped or constant or whatever. The article you probably are referring to is constructing pure academic, but actually non-problem in practice issue out of a tiny design decision about having just one nil literal for all zero values for pointer, slice, map, channel and function types.
Addendum
First, even though nil is typeless on paper, it takes on the error type (by way of it implementing the Error interface combined with Go's duck typing) for the purposes of conforming to might_error's return type signature.
This is a completely wrong description of what happens.
If you write
func f() (r int) { return 7 }
then 7 is assigned to r of type int and f returns. This works because 7 can be assigned to int.
In
func might_error() (int, error) { return 1, nil }
the same happens, the second return variable of type error (an interface type) is set to nil because nil can be assigned to any interface type like you can assign nil to any pointer type or any function type.
This has nothing to do with "implementing the Error interface combined with Go's duck typing". Absolutely not. nil doesn't implement the error interface at all. Any interface value can be nil like can be any function value or slice value or channel value. Setting a chan to nil basically "clears" the channel variable, it doesn't mean that nil somehow "implements the channel interface". You seem to conflate the zero value of several types and how to set them by assigning nil with implementing interfaces. All this has basically nothing to do with nil being typed or not. The nil literal in source code os overloaded and often can be thought of as just representing the zero value of a type.
Your example doesn't compile (because main needs to return nothing), and when you go into picky and nitty areas of a language, all your examples should actually work. 😀
My current line of thinking is that the Error interface is injected into a specific instance of nil in cases where a function's type signature requires it ...
That's not quite right. The Go specification tells us how this works:
There are three ways to return values from a function with a result type:
The return value or values may be explicitly listed in the "return" statement. Each expression must be single-valued and assignable to the corresponding element of the function's result type. [example snipped]
This is the method you use in your example program (which I cleaned up a bit to compile and run in the Go Playground). The expression:
return 1, nil
means:
unnamed_return_variable_1 = 1
unnamed_return_variable_2 = nil
where the two unnamed return variables don't actually have these names (they're un-named, after all) but do have types, courtesy of the declaration of the function. So
return 1, nil
is not at all like:
x, err := 1, nil
but rather more like:
var x int; var err error; x, err = 1, nil
which, as you can see, is also quite valid.
What motivated these design choices?
For that, you'd have to ask the designers.
ThinkGoodly mentions in a comment that:
The untyped 0 does not cause this angst.
The untyped constant 0 has a default type, though:
An untyped constant has a default type which is the type to which the constant is implicitly converted in contexts where a typed value is required, for instance, in a short variable declaration such as i := 0 where there is no explicit type. The default type of an untyped constant is bool, rune, int, float64, complex128 or string respectively, depending on whether it is a boolean, rune, integer, floating-point, complex, or string constant.
The predeclared identifier nil has no type, not even a default type. It just has a series of special rules that allow it to be used in various places.
The non-language-canon way to think about this
While this isn't how it's defined (it's defined by the Go specification), this is how I recommend thinking about the issue:
The predeclared identifier1 nil is untyped.
There are typed nil values. Anything sufficiently pointer-like can be nil, or can be non-nil. For instance, any *int variable can be pointer-to-int-nil, as an uninitialized one is. This nil is not the nil "keyword" (predeclared identifier, see footnote); it's a completely different "nil", just like Bruce (Banner) is a completely different person from Bruce (Wayne).
Interface values are two part: a type, and a value of that type. The type can be nil! This is yet another kind of nil, different from nil (the untyped "keyword") and nil (some particular nil of some particular pointer-y type). If the type is nil, the value can also be nil. If both are nil, the interface value compares equal to the <nil,nil> pair that the untyped "keyword" nil turns into when needed for comparison against an interface value. If either one is non-nil, the comparison says these are not equal. The hardware implementation is that the two parts of the interface are both zero: if either part is nonzero, the thing as a whole is nonzero, and hence "not nil".
The conversion from nil-the-"keyword" (predeclared identifier) to an appropriate hardware style zero value occurs when there's enough information supplied by context. Assignment to some variable—even an unnamed one—supplies context. Assignment to some positional argument supplies context. Trying to use a short declaration fails to supply context, hence the error.
1Go in general favors predeclared identifiers to keywords, so that false and true and so on are not actually keywords. This keeps nil out of the keyword set as well. Nonetheless, some things—such as the boolean constants false and true, or the magical behavior of the predeclared identifier iota, are only accessible by not covering up the predeclared identifier and then using it. That is, if you name something iota, you can't get the iota style functionality until that name goes out of scope. The way these things behave is often handled via keywords in other languages. If you tend to think in, say, C++ or Java, you might want to keep reminding yourself that these aren't keywords, even though they smell like them.
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.
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
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.
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.