从 golang 中的 interface{} 正确转换类型断言失败

这是我从下面的简单重现案例中得到的输出:


2015/06/22 21:09:50 ok: false

2015/06/22 21:09:50 stub: *main.Stub <nil>

显然,存根被正确标记为指向存根类型的指针,但转换失败。我正在尝试更新数组的内容。


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\n", ok)

        log.Printf("stub: %T %+v\n", stub, stub)

        stub.SetValue(1234)

        log.Printf("value:%+v\n", buffer.Get(index)) // I WANT "1234"

    } else {

        log.Printf("ok: %+v\n", ok)

        log.Printf("stub: %T %+v\n", stub, stub) // but this shows the right type

    }


}


喵喵时光机
浏览 427回答 1
1回答

PIPIONE

错误是:func (buf *Buffer) Get(index int) interface{} {&nbsp; &nbsp; return &buf.values[index]}你想做:func (buf *Buffer) Get(index int) interface{} {&nbsp; &nbsp; return buf.values[index]}当您返回 &buf.values[index] 时,您将返回一个指向接口的指针。哪个是 *(*Stub) (在某种意义上)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go