Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cast to interface for implmentation with pointer receiver

I want to check whether an received item of type any implements encoding.TextUnmarshaler, so I can invoke UnmarshalText on it. The problem is, it’s method must be a pointer receiver, and this seems to be the source of quite some trouble.

import (
    "encoding"
    "github.com/stretchr/testify/assert"
    "reflect"
    "testing"
)

type MyStruct struct{ value string }

var _ encoding.TextMarshaler = (*MyStruct)(nil)

func (id MyStruct) MarshalText() (text []byte, err error) {
    return []byte(id.value), nil
}

var _ encoding.TextUnmarshaler = (*MyStruct)(nil)

func (id *MyStruct) UnmarshalText(data []byte) error {
    *id = MyStruct{value: string(data)}
    return nil
}

func TestIfICouldInvokeUnmarshalText(t *testing.T) {
    var ms any = MyStruct{value: "hello"}
    _, ok := (ms).(encoding.TextMarshaler)
    assert.True(t, ok)
    _, ok = (ms).(encoding.TextUnmarshaler)
    //assert.True(t, ok) // this is the first attempt, which will fail
    v := reflect.ValueOf(ms)
    if assert.True(t, v.Type().NumMethod() > 0 && v.CanInterface()) {
        if v.CanAddr() {
            _, ok := v.Addr().Interface().(encoding.TextUnmarshaler)
            assert.True(t, ok)
        } else {
            t.FailNow() // this is where I end up
        }
    }
}

Is there any (idiomatic) way to achieve that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think what you want to do is something like this:

var ms any = MyStruct{value: "hello"}
_, ok := (ms).(encoding.TextMarshaler)
if !ok {
    t.FailNow()
}
_, ok = (ms).(encoding.TextUnmarshaler)
//assert.True(t, ok) // this is the first attempt, which will fail
v := reflect.Indirect(reflect.New(reflect.TypeOf(ms)))
v.Set(reflect.ValueOf(ms))
sp := v.Addr().Interface()
_, ok = (sp).(encoding.TextUnmarshaler)
if !ok {
    t.FailNow()
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading