type SipField interface {
Info() (id, name, defaultValue string, length int)
}
type Field string
func (f *Field) Get() string {
return string(*f)
}
func (f *Field) Set(s string) {
*f = Field(s)
}
type CommandID Field
func (cid *CommandID) Info() (id, name, defaultValue string, length int) {
return "", "command ID", "", 2
}
type Language Field
func (l *Language) Info() (id, name, defaultValue string, length int)
{
return "", "language", "019", 3
}
func InitField(f interface{}, val string) error {
sipField, ok := f.(SipField)
if !ok {
return errors.New("InitField: require a SipField")
}
_, _, defaultValue, length := sipField.Info()
field, ok := f.(*Field)
if !ok {
return errors.New("InitField: require a *Field")
}
return nil
}
How should I do for converting interface{}
to Field(CommandID, Language...)
in InitField()
function? I try to directly type assert by
field, ok := f.(*Field)
but it not working.I have tried to use unsafe.Pointer but failed also.
InitField
with? Your program (minor issues notwithstanding) is syntactically correct and compiles. So the problem must be runtime, and you haven't provided the actual error. – shakurov Mar 23 '18 at 11:23/r/golang
on Reddit, clearly explain the problem (not your solution of it) and solicit for help. – kostix Mar 23 '18 at 11:30f
to*CommandID
and then you can convert that to*Field
like so:(*Field)(f.(*CommandID))
. Type assertionx.(T)
, type conversionT(x)
. See here: play.golang.org/p/m3gHdXRSig5 – mkopriva Mar 23 '18 at 11:36