In Go, Given an interface{} in which I know what interface it implements, how can I convert to it -
my current problem implementing data-structures , have written iterators them. have visible interfaces data-structures, iterators, , other required objects. in have concrete implementations wish hide end user.
this requires many of functions return interface{} objects can store type of object (and leave validation end-user).
one problem have iterate on graph. iterator{} graph implementation returns concrete vertex type iterator interface returns interface{}. since end-users can base vertex interface have try convert vertex interface can use it.
here smallest example think of @ point illustrates issue:
package main import ( "fmt" "strconv" ) type base interface { required() string } type concrete struct { _data int } func (con *concrete) required() string { return strconv.itoa(con._data) } func convert(val interface{}) *base { if con,ok := val.(*base); ok { return con } return nil } func main() { conc := new(concrete) conc._data = 5 base := convert(conc) fmt.println(base) }
in code above wish convert convert type *base. function convert return value nil instead of lovely value wish be.
edit: removed unused code, thought had removed guess not.
now have finished writing long explanation had idea , figured out solution:
func convert(val interface{}) base { if con,ok := val.(base); ok { return con } return nil }
don't try cast pointer rather base interface.
i not sure why case. when reflect.typeof(val) inside of convert gives output
*main.concrete
i hope other people find useful , else can answer why portion of answer.
Comments
Post a Comment