reflect Call method on nested struct

919 views
Skip to first unread message

Sotirios Mantziaris

unread,
May 29, 2019, 3:41:50 AM5/29/19
to golang-nuts
Hi,

i have a nested struct and i want to call a method on a field.


type String struct {
value string
}

func (s *String) Set(value string) {
s.value = value
}

type Config struct {
Name String
}


I am getting the nested "Name" struct but there are no methods to call.
What am i doing wrong (besides using reflection :))?

Check out the playground link?

Jan Mercl

unread,
May 29, 2019, 3:46:32 AM5/29/19
to Sotirios Mantziaris, golang-nuts
On Wed, May 29, 2019 at 9:42 AM Sotirios Mantziaris
<smant...@gmail.com> wrote:

> I am getting the nested "Name" struct but there are no methods to call.
> What am i doing wrong (besides using reflection :))?

The method has a pointer receiver: https://play.golang.org/p/qjhqSvhE9PL

Sotirios Mantziaris

unread,
May 29, 2019, 3:50:58 AM5/29/19
to Jan Mercl, golang-nuts
you are a live saver. thanks very much.
reflection is of of these things in any language i suppose.
--
Regards,

S. Mantziaris

Sotirios Mantziaris

unread,
May 29, 2019, 5:53:13 AM5/29/19
to golang-nuts
I did found out that the setter method has to accept a pointer to string.
I have a complete example now which unfortunately don't work correclty. The value should change but it is emptied out.

https://play.golang.org/p/OPZKltApEhF

What am i missing?

Sotirios Mantziaris

unread,
May 29, 2019, 5:56:42 AM5/29/19
to golang-nuts
Ok, found it. I should have used the reflect.ValueOf...

Max

unread,
May 29, 2019, 6:56:14 AM5/29/19
to golang-nuts
There is another improvement you can do: you are currently using

cfg := Config{Name: &nameField}
r := reflect.ValueOf(cfg)

which means that 'r' will contain a copy of 'cfg' and will not be settable.
If instead you use:

r := reflect.ValueOf(&cfg).Elem()

then r will contain a *pointer* to the original 'cfg' and can modify it (the reflect.Value 'r' is settable).
In turn, this also allows to declare 'Config' as follows:
```
type Config struct {
    Name String
}
```
i.e. removes the need to use a *pointer* to String.
You also need some minor adjustments to the rest of the code...

A complete example is:

Sotirios Mantziaris

unread,
May 29, 2019, 8:46:48 AM5/29/19
to golang-nuts
Hi Max, 
this makes the config even simpler since i do not need to be sure that the field is nil.
I will try this out for sure.
Reply all
Reply to author
Forward
0 new messages