第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 golang 中的 interface{} 正確轉換類型斷言失敗

從 golang 中的 interface{} 正確轉換類型斷言失敗

Go
喵喵時光機 2021-10-18 14:07:01
這是我從下面的簡單重現(xiàn)案例中得到的輸出:2015/06/22 21:09:50 ok: false2015/06/22 21:09:50 stub: *main.Stub <nil>顯然,存根被正確標記為指向存根類型的指針,但轉換失敗。我正在嘗試更新數(shù)組的內容。package mainimport "log"const BUFFER_SIZE = 8type 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    }}
查看完整描述

1 回答

?
PIPIONE

TA貢獻1829條經驗 獲得超9個贊

錯誤是:


func (buf *Buffer) Get(index int) interface{} {

    return &buf.values[index]

}

你想做:


func (buf *Buffer) Get(index int) interface{} {

    return buf.values[index]

}

當您返回 &buf.values[index] 時,您將返回一個指向接口的指針。哪個是 *(*Stub) (在某種意義上)


查看完整回答
反對 回復 2021-10-18
  • 1 回答
  • 0 關注
  • 446 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號