Calling a function on element of struct which is a nil pointerUsing reflect, how do you set the value of a struct field?In Go, if type T2 is based on type T1, is there any sort of “inheritance” from T1 to T2?In Go, one type is coerced into another, can a method to determine the type of the receiver?How to dump methods of structs in Golang?golang - function in map is <nil>passing array (not pointer) to a struct in cPointer to constant string in structGolang set nil string pointer value in struct using reflectGolang struct pointer invokes interface methodAssign additional field when unmarshalling JSON object to GO struct
Can compressed videos be decoded back to their uncompresed original format?
What are some good books on Machine Learning and AI like Krugman, Wells and Graddy's "Essentials of Economics"
How can I deal with my CEO asking me to hire someone with a higher salary than me, a co-founder?
Mathematica command that allows it to read my intentions
How dangerous is XSS?
Can I run a new neutral wire to repair a broken circuit?
Is it acceptable for a professor to tell male students to not think that they are smarter than female students?
I would say: "You are another teacher", but she is a woman and I am a man
Plagiarism or not?
What killed these X2 caps?
When (not how or why) to calculate Big O of an algorithm
Can we compute the area of a quadrilateral with one right angle when we only know the lengths of any three sides?
GFCI outlets - can they be repaired? Are they really needed at the end of a circuit?
What method can I use to design a dungeon difficult enough that the PCs can't make it through without killing them?
Is there a hemisphere-neutral way of specifying a season?
Expand and Contract
Determining Impedance With An Antenna Analyzer
One verb to replace 'be a member of' a club
Does the Idaho Potato Commission associate potato skins with healthy eating?
If human space travel is limited by the G force vulnerability, is there a way to counter G forces?
Should I tell management that I intend to leave due to bad software development practices?
Venezuelan girlfriend wants to travel the USA to be with me. What is the process?
How to show a landlord what we have in savings?
Avoiding the "not like other girls" trope?
Calling a function on element of struct which is a nil pointer
Using reflect, how do you set the value of a struct field?In Go, if type T2 is based on type T1, is there any sort of “inheritance” from T1 to T2?In Go, one type is coerced into another, can a method to determine the type of the receiver?How to dump methods of structs in Golang?golang - function in map is <nil>passing array (not pointer) to a struct in cPointer to constant string in structGolang set nil string pointer value in struct using reflectGolang struct pointer invokes interface methodAssign additional field when unmarshalling JSON object to GO struct
In Go, however, the function to be called by the Expression.Name() syntax is entirely determined by the type of Expression and not by the particular run-time value of that expression, including nil - copied
So we can call a method using a struct instance which is nil.
Consider the following program:
package main
import "fmt"
type T struct
V int
tt *T
func (t *T) hello() string
return "world"
func main()
var t *T = nil
fmt.Println(t, t.hello()) // <nil> world
fmt.Println(t, t.tt.hello()) // panic
Why fmt.Println(t, t.hello()) worked?
But
fmt.Println(t, t.tt.hello()) panicked?.
My understanding is that both t and t.tt are nil pointers. So t.tt.hello() should not panic as Calling a method on a nil struct pointer is allowed in golang.
go struct
add a comment |
In Go, however, the function to be called by the Expression.Name() syntax is entirely determined by the type of Expression and not by the particular run-time value of that expression, including nil - copied
So we can call a method using a struct instance which is nil.
Consider the following program:
package main
import "fmt"
type T struct
V int
tt *T
func (t *T) hello() string
return "world"
func main()
var t *T = nil
fmt.Println(t, t.hello()) // <nil> world
fmt.Println(t, t.tt.hello()) // panic
Why fmt.Println(t, t.hello()) worked?
But
fmt.Println(t, t.tt.hello()) panicked?.
My understanding is that both t and t.tt are nil pointers. So t.tt.hello() should not panic as Calling a method on a nil struct pointer is allowed in golang.
go struct
add a comment |
In Go, however, the function to be called by the Expression.Name() syntax is entirely determined by the type of Expression and not by the particular run-time value of that expression, including nil - copied
So we can call a method using a struct instance which is nil.
Consider the following program:
package main
import "fmt"
type T struct
V int
tt *T
func (t *T) hello() string
return "world"
func main()
var t *T = nil
fmt.Println(t, t.hello()) // <nil> world
fmt.Println(t, t.tt.hello()) // panic
Why fmt.Println(t, t.hello()) worked?
But
fmt.Println(t, t.tt.hello()) panicked?.
My understanding is that both t and t.tt are nil pointers. So t.tt.hello() should not panic as Calling a method on a nil struct pointer is allowed in golang.
go struct
In Go, however, the function to be called by the Expression.Name() syntax is entirely determined by the type of Expression and not by the particular run-time value of that expression, including nil - copied
So we can call a method using a struct instance which is nil.
Consider the following program:
package main
import "fmt"
type T struct
V int
tt *T
func (t *T) hello() string
return "world"
func main()
var t *T = nil
fmt.Println(t, t.hello()) // <nil> world
fmt.Println(t, t.tt.hello()) // panic
Why fmt.Println(t, t.hello()) worked?
But
fmt.Println(t, t.tt.hello()) panicked?.
My understanding is that both t and t.tt are nil pointers. So t.tt.hello() should not panic as Calling a method on a nil struct pointer is allowed in golang.
go struct
go struct
edited Mar 9 at 15:38
Prakash Pandey
asked Mar 8 at 22:20
Prakash PandeyPrakash Pandey
75911432
75911432
add a comment |
add a comment |
4 Answers
4
active
oldest
votes
My understanding is that both t and t.tt are nil pointers. So
t.tt.hello() should not panic as Calling a method on a nil struct
pointer is allowed in golang.
Your "understanding" is wrong.t.tt should and does panic.
Go 1.2 Release Notes (December 2013)
Use of nil
The language now specifies that, for safety reasons, certain uses of
nil pointers are guaranteed to trigger a run-time panic. For instance,
in Go 1.0, given code liketype T struct
X [1<<24]byte
Field int32
func main()
var x *T
...
the nil pointer x could be used to access memory incorrectly: the
expression x.Field could access memory at address 1<<24. To prevent
such unsafe behavior, in Go 1.2 the compilers now guarantee that any
indirection through a nil pointer, such as illustrated here but also
in nil pointers to arrays, nil interface values, nil slices, and so
on, will either panic or return a correct, safe non-nil value. In
short, any expression that explicitly or implicitly requires
evaluation of a nil address is an error. The implementation may inject
extra tests into the compiled program to enforce this behavior.
Further details are in the design document.
In short, any expression that explicitly or implicitly requires
evaluation of a nil address is an error.
Therefore, the following behavior is expected. The indirection for t.tt through a nil value of t fails with a panic.
package main
import "fmt"
type T struct
V int
tt *T
func (t *T) hello() string
return "world"
type A struct
a int
func main()
var t *T = nil
fmt.Println(t) // nil
fmt.Println(t.tt.hello()) // panic
Playground: https://play.golang.org/p/Szwx5MqNHkQ
Output:
<nil>
panic: runtime error: invalid memory address or nil pointer dereference
main.main()
/tmp/sandbox136049644/main.go:21 +0x84
add a comment |
Precisely speaking, t is a nil pointer, and t.tt doesn't exist at all. The panic you see is the result of dereferencing t, not t.tt. This is just obscured by the fact that t.tt is (or would be, if t were initialized) also a pointer.
This can be made more clear by accessing the V field of t:
func (t *T) foo()
fmt.Println(t.V) // Will panic, if `t` is nil
The reason the first test doesn't panic is that calling a method on t doesn't actually dereference t. Calling t.Hello() is roughly the equivalent of calling Hello(t), so won't panic unless/until t is actually dereferenced within the function.
add a comment |
t is nil,there is no t.tt.
And t.hello() is like hello(t), hello(nil) don't panic, but t.tt do.
Remember: a method is just a function with a receiver argument.
Method expressions
add a comment |
nil is the zero value for pointers
// nil is a predeclared identifier representing the zero value for a
// pointer, channel, func, interface, map, or slice type.
var nil Type // Type must be a pointer, channel, func, interface, map, or slice type
Source: https://golang.org/src/builtin/builtin.go?h=nil#L101
To understand nil this video is fantastic
https://www.youtube.com/watch?v=ynoY2xz-F8s
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071801%2fcalling-a-function-on-element-of-struct-which-is-a-nil-pointer%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
4 Answers
4
active
oldest
votes
4 Answers
4
active
oldest
votes
active
oldest
votes
active
oldest
votes
My understanding is that both t and t.tt are nil pointers. So
t.tt.hello() should not panic as Calling a method on a nil struct
pointer is allowed in golang.
Your "understanding" is wrong.t.tt should and does panic.
Go 1.2 Release Notes (December 2013)
Use of nil
The language now specifies that, for safety reasons, certain uses of
nil pointers are guaranteed to trigger a run-time panic. For instance,
in Go 1.0, given code liketype T struct
X [1<<24]byte
Field int32
func main()
var x *T
...
the nil pointer x could be used to access memory incorrectly: the
expression x.Field could access memory at address 1<<24. To prevent
such unsafe behavior, in Go 1.2 the compilers now guarantee that any
indirection through a nil pointer, such as illustrated here but also
in nil pointers to arrays, nil interface values, nil slices, and so
on, will either panic or return a correct, safe non-nil value. In
short, any expression that explicitly or implicitly requires
evaluation of a nil address is an error. The implementation may inject
extra tests into the compiled program to enforce this behavior.
Further details are in the design document.
In short, any expression that explicitly or implicitly requires
evaluation of a nil address is an error.
Therefore, the following behavior is expected. The indirection for t.tt through a nil value of t fails with a panic.
package main
import "fmt"
type T struct
V int
tt *T
func (t *T) hello() string
return "world"
type A struct
a int
func main()
var t *T = nil
fmt.Println(t) // nil
fmt.Println(t.tt.hello()) // panic
Playground: https://play.golang.org/p/Szwx5MqNHkQ
Output:
<nil>
panic: runtime error: invalid memory address or nil pointer dereference
main.main()
/tmp/sandbox136049644/main.go:21 +0x84
add a comment |
My understanding is that both t and t.tt are nil pointers. So
t.tt.hello() should not panic as Calling a method on a nil struct
pointer is allowed in golang.
Your "understanding" is wrong.t.tt should and does panic.
Go 1.2 Release Notes (December 2013)
Use of nil
The language now specifies that, for safety reasons, certain uses of
nil pointers are guaranteed to trigger a run-time panic. For instance,
in Go 1.0, given code liketype T struct
X [1<<24]byte
Field int32
func main()
var x *T
...
the nil pointer x could be used to access memory incorrectly: the
expression x.Field could access memory at address 1<<24. To prevent
such unsafe behavior, in Go 1.2 the compilers now guarantee that any
indirection through a nil pointer, such as illustrated here but also
in nil pointers to arrays, nil interface values, nil slices, and so
on, will either panic or return a correct, safe non-nil value. In
short, any expression that explicitly or implicitly requires
evaluation of a nil address is an error. The implementation may inject
extra tests into the compiled program to enforce this behavior.
Further details are in the design document.
In short, any expression that explicitly or implicitly requires
evaluation of a nil address is an error.
Therefore, the following behavior is expected. The indirection for t.tt through a nil value of t fails with a panic.
package main
import "fmt"
type T struct
V int
tt *T
func (t *T) hello() string
return "world"
type A struct
a int
func main()
var t *T = nil
fmt.Println(t) // nil
fmt.Println(t.tt.hello()) // panic
Playground: https://play.golang.org/p/Szwx5MqNHkQ
Output:
<nil>
panic: runtime error: invalid memory address or nil pointer dereference
main.main()
/tmp/sandbox136049644/main.go:21 +0x84
add a comment |
My understanding is that both t and t.tt are nil pointers. So
t.tt.hello() should not panic as Calling a method on a nil struct
pointer is allowed in golang.
Your "understanding" is wrong.t.tt should and does panic.
Go 1.2 Release Notes (December 2013)
Use of nil
The language now specifies that, for safety reasons, certain uses of
nil pointers are guaranteed to trigger a run-time panic. For instance,
in Go 1.0, given code liketype T struct
X [1<<24]byte
Field int32
func main()
var x *T
...
the nil pointer x could be used to access memory incorrectly: the
expression x.Field could access memory at address 1<<24. To prevent
such unsafe behavior, in Go 1.2 the compilers now guarantee that any
indirection through a nil pointer, such as illustrated here but also
in nil pointers to arrays, nil interface values, nil slices, and so
on, will either panic or return a correct, safe non-nil value. In
short, any expression that explicitly or implicitly requires
evaluation of a nil address is an error. The implementation may inject
extra tests into the compiled program to enforce this behavior.
Further details are in the design document.
In short, any expression that explicitly or implicitly requires
evaluation of a nil address is an error.
Therefore, the following behavior is expected. The indirection for t.tt through a nil value of t fails with a panic.
package main
import "fmt"
type T struct
V int
tt *T
func (t *T) hello() string
return "world"
type A struct
a int
func main()
var t *T = nil
fmt.Println(t) // nil
fmt.Println(t.tt.hello()) // panic
Playground: https://play.golang.org/p/Szwx5MqNHkQ
Output:
<nil>
panic: runtime error: invalid memory address or nil pointer dereference
main.main()
/tmp/sandbox136049644/main.go:21 +0x84
My understanding is that both t and t.tt are nil pointers. So
t.tt.hello() should not panic as Calling a method on a nil struct
pointer is allowed in golang.
Your "understanding" is wrong.t.tt should and does panic.
Go 1.2 Release Notes (December 2013)
Use of nil
The language now specifies that, for safety reasons, certain uses of
nil pointers are guaranteed to trigger a run-time panic. For instance,
in Go 1.0, given code liketype T struct
X [1<<24]byte
Field int32
func main()
var x *T
...
the nil pointer x could be used to access memory incorrectly: the
expression x.Field could access memory at address 1<<24. To prevent
such unsafe behavior, in Go 1.2 the compilers now guarantee that any
indirection through a nil pointer, such as illustrated here but also
in nil pointers to arrays, nil interface values, nil slices, and so
on, will either panic or return a correct, safe non-nil value. In
short, any expression that explicitly or implicitly requires
evaluation of a nil address is an error. The implementation may inject
extra tests into the compiled program to enforce this behavior.
Further details are in the design document.
In short, any expression that explicitly or implicitly requires
evaluation of a nil address is an error.
Therefore, the following behavior is expected. The indirection for t.tt through a nil value of t fails with a panic.
package main
import "fmt"
type T struct
V int
tt *T
func (t *T) hello() string
return "world"
type A struct
a int
func main()
var t *T = nil
fmt.Println(t) // nil
fmt.Println(t.tt.hello()) // panic
Playground: https://play.golang.org/p/Szwx5MqNHkQ
Output:
<nil>
panic: runtime error: invalid memory address or nil pointer dereference
main.main()
/tmp/sandbox136049644/main.go:21 +0x84
edited Mar 8 at 23:36
answered Mar 8 at 23:25
peterSOpeterSO
98.7k16167182
98.7k16167182
add a comment |
add a comment |
Precisely speaking, t is a nil pointer, and t.tt doesn't exist at all. The panic you see is the result of dereferencing t, not t.tt. This is just obscured by the fact that t.tt is (or would be, if t were initialized) also a pointer.
This can be made more clear by accessing the V field of t:
func (t *T) foo()
fmt.Println(t.V) // Will panic, if `t` is nil
The reason the first test doesn't panic is that calling a method on t doesn't actually dereference t. Calling t.Hello() is roughly the equivalent of calling Hello(t), so won't panic unless/until t is actually dereferenced within the function.
add a comment |
Precisely speaking, t is a nil pointer, and t.tt doesn't exist at all. The panic you see is the result of dereferencing t, not t.tt. This is just obscured by the fact that t.tt is (or would be, if t were initialized) also a pointer.
This can be made more clear by accessing the V field of t:
func (t *T) foo()
fmt.Println(t.V) // Will panic, if `t` is nil
The reason the first test doesn't panic is that calling a method on t doesn't actually dereference t. Calling t.Hello() is roughly the equivalent of calling Hello(t), so won't panic unless/until t is actually dereferenced within the function.
add a comment |
Precisely speaking, t is a nil pointer, and t.tt doesn't exist at all. The panic you see is the result of dereferencing t, not t.tt. This is just obscured by the fact that t.tt is (or would be, if t were initialized) also a pointer.
This can be made more clear by accessing the V field of t:
func (t *T) foo()
fmt.Println(t.V) // Will panic, if `t` is nil
The reason the first test doesn't panic is that calling a method on t doesn't actually dereference t. Calling t.Hello() is roughly the equivalent of calling Hello(t), so won't panic unless/until t is actually dereferenced within the function.
Precisely speaking, t is a nil pointer, and t.tt doesn't exist at all. The panic you see is the result of dereferencing t, not t.tt. This is just obscured by the fact that t.tt is (or would be, if t were initialized) also a pointer.
This can be made more clear by accessing the V field of t:
func (t *T) foo()
fmt.Println(t.V) // Will panic, if `t` is nil
The reason the first test doesn't panic is that calling a method on t doesn't actually dereference t. Calling t.Hello() is roughly the equivalent of calling Hello(t), so won't panic unless/until t is actually dereferenced within the function.
edited Mar 9 at 12:04
answered Mar 8 at 22:51
FlimzyFlimzy
40.4k1367101
40.4k1367101
add a comment |
add a comment |
t is nil,there is no t.tt.
And t.hello() is like hello(t), hello(nil) don't panic, but t.tt do.
Remember: a method is just a function with a receiver argument.
Method expressions
add a comment |
t is nil,there is no t.tt.
And t.hello() is like hello(t), hello(nil) don't panic, but t.tt do.
Remember: a method is just a function with a receiver argument.
Method expressions
add a comment |
t is nil,there is no t.tt.
And t.hello() is like hello(t), hello(nil) don't panic, but t.tt do.
Remember: a method is just a function with a receiver argument.
Method expressions
t is nil,there is no t.tt.
And t.hello() is like hello(t), hello(nil) don't panic, but t.tt do.
Remember: a method is just a function with a receiver argument.
Method expressions
edited Mar 9 at 14:04
answered Mar 9 at 8:24
Yates XingYates Xing
213
213
add a comment |
add a comment |
nil is the zero value for pointers
// nil is a predeclared identifier representing the zero value for a
// pointer, channel, func, interface, map, or slice type.
var nil Type // Type must be a pointer, channel, func, interface, map, or slice type
Source: https://golang.org/src/builtin/builtin.go?h=nil#L101
To understand nil this video is fantastic
https://www.youtube.com/watch?v=ynoY2xz-F8s
add a comment |
nil is the zero value for pointers
// nil is a predeclared identifier representing the zero value for a
// pointer, channel, func, interface, map, or slice type.
var nil Type // Type must be a pointer, channel, func, interface, map, or slice type
Source: https://golang.org/src/builtin/builtin.go?h=nil#L101
To understand nil this video is fantastic
https://www.youtube.com/watch?v=ynoY2xz-F8s
add a comment |
nil is the zero value for pointers
// nil is a predeclared identifier representing the zero value for a
// pointer, channel, func, interface, map, or slice type.
var nil Type // Type must be a pointer, channel, func, interface, map, or slice type
Source: https://golang.org/src/builtin/builtin.go?h=nil#L101
To understand nil this video is fantastic
https://www.youtube.com/watch?v=ynoY2xz-F8s
nil is the zero value for pointers
// nil is a predeclared identifier representing the zero value for a
// pointer, channel, func, interface, map, or slice type.
var nil Type // Type must be a pointer, channel, func, interface, map, or slice type
Source: https://golang.org/src/builtin/builtin.go?h=nil#L101
To understand nil this video is fantastic
https://www.youtube.com/watch?v=ynoY2xz-F8s
edited Mar 8 at 22:52
answered Mar 8 at 22:45
Hernan GarciaHernan Garcia
614515
614515
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071801%2fcalling-a-function-on-element-of-struct-which-is-a-nil-pointer%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown