golang 无法为结构分配接口 {}

专家您好,我正在使用此库将 K/V 存储在缓存中


"github.com/bluele/gcache"


我存储的值就是这个数据结构


type LatestBlockhashCacheResult struct {

    Blockhash            string `json:"blockhash"`

    LastValidBlockHeight uint64 `json:"lastValidBlockHeight"` // Slot.

    CommitmentType  string `json:"commitmentType"`

}

lbhr := LatestBlockhashCacheResult{

            Blockhash:            lbh.Value.Blockhash.String(),

            LastValidBlockHeight: lbh.Value.LastValidBlockHeight,

            CommitmentType:       string(commitmentType),

        }

        gc.SetWithExpire(lbh.Value.LastValidBlockHeight, lbhr, time.Hour*10)


我对检索缓存没有问题,但无法对其进行类型转换


c, _ := gc.Get(rf.LastValidBlockHeight)

    fmt.Printf("%T\n", c)

所以当我尝试这个


var c = LatestBlockhashCacheResult{}

    c, _ = gc.Get(rf.LastValidBlockHeight)

这引发了我的错误


 cannot assign interface {} to c (type LatestBlockhashCacheResult) in multiple assignment: need type assertion


婷婷同学_
浏览 149回答 1
1回答

MYYA

您正在尝试分配interface{}给类型化变量。为此,您需要首先尝试将interface{}值转换为特定类型val, err := gc.Get(rf.LastValidBlockHeight)if err != nil {  // handle }c, ok := val.(LatestBlockhashCacheResult)if !ok {   // val has different type than LatestBlockhashCacheResult}参考:https://go.dev/tour/methods/15https://go.dev/tour/methods/16
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go