Dereference struct pointer and access fields with reflection
I'm writing a recursive function that iterates through every primitive field in a struct.
I need to be able to support fields that are structs, pointers to structs, fields, and pointers to fields.
I've tried doing something like this, where for each field, I first do a check if it's a pointer. If it is, I switch on the type of that instead of just the field itself.
//Get reflect values and types
valOf := reflect.ValueOf(dest).Elem()
typeOf := valOf.Type()
//Iterate through each field
for i := 0; i < valOf.NumField(); i++ {
var fieldValDeref reflect.Value
//Get reflect value and type of single field
fieldVal := valOf.Field(i)
fieldTyp := typeOf.Field(i)
//Check if field is a pointer. If so, dereference and switch on dereferenced type
if fieldVal.Kind() == reflect.Ptr {
fieldValDeref = fieldVal.Elem()
} else {
fieldValDeref = fieldVal
}
switch fieldValDeref.Kind() {
case reflect.Array, reflect.Chan, reflect.Interface, reflect.Func, reflect.Map, reflect.UnsafePointer:
return errors.New("invalid destination field: " + fieldTyp.Name)
case reflect.Struct:
//Recursive call
break
default:
//Perform Action on Field
..................................
The issue I'm getting with this, is that the type of any pointer, struct or not, after calling .Elem()
is reflect.Invalid
.
How can I first dereference a field (if it is a pointer) and then perform actions accordingly, whether the field is a struct or a primitive?
Thanks
go reflection
add a comment |
I'm writing a recursive function that iterates through every primitive field in a struct.
I need to be able to support fields that are structs, pointers to structs, fields, and pointers to fields.
I've tried doing something like this, where for each field, I first do a check if it's a pointer. If it is, I switch on the type of that instead of just the field itself.
//Get reflect values and types
valOf := reflect.ValueOf(dest).Elem()
typeOf := valOf.Type()
//Iterate through each field
for i := 0; i < valOf.NumField(); i++ {
var fieldValDeref reflect.Value
//Get reflect value and type of single field
fieldVal := valOf.Field(i)
fieldTyp := typeOf.Field(i)
//Check if field is a pointer. If so, dereference and switch on dereferenced type
if fieldVal.Kind() == reflect.Ptr {
fieldValDeref = fieldVal.Elem()
} else {
fieldValDeref = fieldVal
}
switch fieldValDeref.Kind() {
case reflect.Array, reflect.Chan, reflect.Interface, reflect.Func, reflect.Map, reflect.UnsafePointer:
return errors.New("invalid destination field: " + fieldTyp.Name)
case reflect.Struct:
//Recursive call
break
default:
//Perform Action on Field
..................................
The issue I'm getting with this, is that the type of any pointer, struct or not, after calling .Elem()
is reflect.Invalid
.
How can I first dereference a field (if it is a pointer) and then perform actions accordingly, whether the field is a struct or a primitive?
Thanks
go reflection
2
Dereferencing an uninitialized, ienil
, pointer will always result inreflect.Invalid
. See here (play.golang.com/p/8UgDtqK_8ra). To avoid this you have to initialize the field's value which you can do withreflect.New
– mkopriva
Jan 2 at 20:54
... here's an example: play.golang.com/p/q71J0qTQECP
– mkopriva
Jan 2 at 20:58
Would reflectively creating a zero value instance of it first before dereferencing solve this?
– robbieperry22
Jan 2 at 20:59
Does the code in the second comment not already answer your question?
– mkopriva
Jan 2 at 21:03
1
It does, thanks. Comments didn't refresh when I replied.
– robbieperry22
Jan 2 at 21:11
add a comment |
I'm writing a recursive function that iterates through every primitive field in a struct.
I need to be able to support fields that are structs, pointers to structs, fields, and pointers to fields.
I've tried doing something like this, where for each field, I first do a check if it's a pointer. If it is, I switch on the type of that instead of just the field itself.
//Get reflect values and types
valOf := reflect.ValueOf(dest).Elem()
typeOf := valOf.Type()
//Iterate through each field
for i := 0; i < valOf.NumField(); i++ {
var fieldValDeref reflect.Value
//Get reflect value and type of single field
fieldVal := valOf.Field(i)
fieldTyp := typeOf.Field(i)
//Check if field is a pointer. If so, dereference and switch on dereferenced type
if fieldVal.Kind() == reflect.Ptr {
fieldValDeref = fieldVal.Elem()
} else {
fieldValDeref = fieldVal
}
switch fieldValDeref.Kind() {
case reflect.Array, reflect.Chan, reflect.Interface, reflect.Func, reflect.Map, reflect.UnsafePointer:
return errors.New("invalid destination field: " + fieldTyp.Name)
case reflect.Struct:
//Recursive call
break
default:
//Perform Action on Field
..................................
The issue I'm getting with this, is that the type of any pointer, struct or not, after calling .Elem()
is reflect.Invalid
.
How can I first dereference a field (if it is a pointer) and then perform actions accordingly, whether the field is a struct or a primitive?
Thanks
go reflection
I'm writing a recursive function that iterates through every primitive field in a struct.
I need to be able to support fields that are structs, pointers to structs, fields, and pointers to fields.
I've tried doing something like this, where for each field, I first do a check if it's a pointer. If it is, I switch on the type of that instead of just the field itself.
//Get reflect values and types
valOf := reflect.ValueOf(dest).Elem()
typeOf := valOf.Type()
//Iterate through each field
for i := 0; i < valOf.NumField(); i++ {
var fieldValDeref reflect.Value
//Get reflect value and type of single field
fieldVal := valOf.Field(i)
fieldTyp := typeOf.Field(i)
//Check if field is a pointer. If so, dereference and switch on dereferenced type
if fieldVal.Kind() == reflect.Ptr {
fieldValDeref = fieldVal.Elem()
} else {
fieldValDeref = fieldVal
}
switch fieldValDeref.Kind() {
case reflect.Array, reflect.Chan, reflect.Interface, reflect.Func, reflect.Map, reflect.UnsafePointer:
return errors.New("invalid destination field: " + fieldTyp.Name)
case reflect.Struct:
//Recursive call
break
default:
//Perform Action on Field
..................................
The issue I'm getting with this, is that the type of any pointer, struct or not, after calling .Elem()
is reflect.Invalid
.
How can I first dereference a field (if it is a pointer) and then perform actions accordingly, whether the field is a struct or a primitive?
Thanks
go reflection
go reflection
asked Jan 2 at 20:28
robbieperry22robbieperry22
192117
192117
2
Dereferencing an uninitialized, ienil
, pointer will always result inreflect.Invalid
. See here (play.golang.com/p/8UgDtqK_8ra). To avoid this you have to initialize the field's value which you can do withreflect.New
– mkopriva
Jan 2 at 20:54
... here's an example: play.golang.com/p/q71J0qTQECP
– mkopriva
Jan 2 at 20:58
Would reflectively creating a zero value instance of it first before dereferencing solve this?
– robbieperry22
Jan 2 at 20:59
Does the code in the second comment not already answer your question?
– mkopriva
Jan 2 at 21:03
1
It does, thanks. Comments didn't refresh when I replied.
– robbieperry22
Jan 2 at 21:11
add a comment |
2
Dereferencing an uninitialized, ienil
, pointer will always result inreflect.Invalid
. See here (play.golang.com/p/8UgDtqK_8ra). To avoid this you have to initialize the field's value which you can do withreflect.New
– mkopriva
Jan 2 at 20:54
... here's an example: play.golang.com/p/q71J0qTQECP
– mkopriva
Jan 2 at 20:58
Would reflectively creating a zero value instance of it first before dereferencing solve this?
– robbieperry22
Jan 2 at 20:59
Does the code in the second comment not already answer your question?
– mkopriva
Jan 2 at 21:03
1
It does, thanks. Comments didn't refresh when I replied.
– robbieperry22
Jan 2 at 21:11
2
2
Dereferencing an uninitialized, ie
nil
, pointer will always result in reflect.Invalid
. See here (play.golang.com/p/8UgDtqK_8ra). To avoid this you have to initialize the field's value which you can do with reflect.New
– mkopriva
Jan 2 at 20:54
Dereferencing an uninitialized, ie
nil
, pointer will always result in reflect.Invalid
. See here (play.golang.com/p/8UgDtqK_8ra). To avoid this you have to initialize the field's value which you can do with reflect.New
– mkopriva
Jan 2 at 20:54
... here's an example: play.golang.com/p/q71J0qTQECP
– mkopriva
Jan 2 at 20:58
... here's an example: play.golang.com/p/q71J0qTQECP
– mkopriva
Jan 2 at 20:58
Would reflectively creating a zero value instance of it first before dereferencing solve this?
– robbieperry22
Jan 2 at 20:59
Would reflectively creating a zero value instance of it first before dereferencing solve this?
– robbieperry22
Jan 2 at 20:59
Does the code in the second comment not already answer your question?
– mkopriva
Jan 2 at 21:03
Does the code in the second comment not already answer your question?
– mkopriva
Jan 2 at 21:03
1
1
It does, thanks. Comments didn't refresh when I replied.
– robbieperry22
Jan 2 at 21:11
It does, thanks. Comments didn't refresh when I replied.
– robbieperry22
Jan 2 at 21:11
add a comment |
1 Answer
1
active
oldest
votes
As mkopriva mentioned, dereferencing a nil pointer will always return reflect.Invalid
. The solution is to create a new instance first.
if fieldVal.Kind() == reflect.Ptr {
fieldVal.Set(reflect.New(fieldVal.Type().Elem()))
fieldValDeref = fieldVal.Elem()
} else {
fieldValDeref = fieldVal
}
add a comment |
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%2f54012738%2fdereference-struct-pointer-and-access-fields-with-reflection%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
As mkopriva mentioned, dereferencing a nil pointer will always return reflect.Invalid
. The solution is to create a new instance first.
if fieldVal.Kind() == reflect.Ptr {
fieldVal.Set(reflect.New(fieldVal.Type().Elem()))
fieldValDeref = fieldVal.Elem()
} else {
fieldValDeref = fieldVal
}
add a comment |
As mkopriva mentioned, dereferencing a nil pointer will always return reflect.Invalid
. The solution is to create a new instance first.
if fieldVal.Kind() == reflect.Ptr {
fieldVal.Set(reflect.New(fieldVal.Type().Elem()))
fieldValDeref = fieldVal.Elem()
} else {
fieldValDeref = fieldVal
}
add a comment |
As mkopriva mentioned, dereferencing a nil pointer will always return reflect.Invalid
. The solution is to create a new instance first.
if fieldVal.Kind() == reflect.Ptr {
fieldVal.Set(reflect.New(fieldVal.Type().Elem()))
fieldValDeref = fieldVal.Elem()
} else {
fieldValDeref = fieldVal
}
As mkopriva mentioned, dereferencing a nil pointer will always return reflect.Invalid
. The solution is to create a new instance first.
if fieldVal.Kind() == reflect.Ptr {
fieldVal.Set(reflect.New(fieldVal.Type().Elem()))
fieldValDeref = fieldVal.Elem()
} else {
fieldValDeref = fieldVal
}
answered Jan 2 at 21:16
robbieperry22robbieperry22
192117
192117
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%2f54012738%2fdereference-struct-pointer-and-access-fields-with-reflection%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
2
Dereferencing an uninitialized, ie
nil
, pointer will always result inreflect.Invalid
. See here (play.golang.com/p/8UgDtqK_8ra). To avoid this you have to initialize the field's value which you can do withreflect.New
– mkopriva
Jan 2 at 20:54
... here's an example: play.golang.com/p/q71J0qTQECP
– mkopriva
Jan 2 at 20:58
Would reflectively creating a zero value instance of it first before dereferencing solve this?
– robbieperry22
Jan 2 at 20:59
Does the code in the second comment not already answer your question?
– mkopriva
Jan 2 at 21:03
1
It does, thanks. Comments didn't refresh when I replied.
– robbieperry22
Jan 2 at 21:11