douci1677 2015-06-23 04:13
浏览 554
已采纳

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

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
    }

}
  • 写回答

1条回答 默认 最新

  • douji0588 2015-06-23 04:39
    关注

    The error is:

    func (buf *Buffer) Get(index int) interface{} {
        return &buf.values[index]
    }
    

    You want to do:

    func (buf *Buffer) Get(index int) interface{} {
        return buf.values[index]
    }
    

    When you return &buf.values[index] you are returning a pointer to an interface. Which is a *(*Stub) (in a sense)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败