Here is the output I am getting from the simple repro case below:
2015/06/22 21:09:50 ok: false
2015/06/22 21:09:50 stub: *main.Stub <nil>
Clearly the stub is correctly marked as pointer to Stub type but the casting failed. I am trying to update the content of the array.
package main
import "log"
const BUFFER_SIZE = 8
type Value struct {
value int
}
func (v Value) Value() int { return v.value }
func (v *Value) SetValue(value int) { v.value = value }
type Stub struct {
Value
testString string
}
type StubFactory struct{}
type FactoryInterface interface {
NewInstance(size int) []interface{}
}
func (factory StubFactory) NewInstance(size int) []interface{} {
stubs := make([]interface{}, size)
for i, _ := range stubs {
stubs[i] = &Stub{Value: Value{i}, testString: ""}
}
return stubs
}
type Buffer struct {
values []interface{}
}
func NewBuffer(factory FactoryInterface, size int) *Buffer {
return &Buffer{values: factory.NewInstance(size)}
}
func (buf *Buffer) Get(index int) interface{} {
return &buf.values[index]
}
func main() {
stubFactory := &StubFactory{}
buffer := NewBuffer(stubFactory, BUFFER_SIZE)
index := 0
if stub, ok := buffer.Get(index).(*Stub); ok { // THIS FAILS :-(
log.Printf("ok: %+v
", ok)
log.Printf("stub: %T %+v
", stub, stub)
stub.SetValue(1234)
log.Printf("value:%+v
", buffer.Get(index)) // I WANT "1234"
} else {
log.Printf("ok: %+v
", ok)
log.Printf("stub: %T %+v
", stub, stub) // but this shows the right type
}
}