golang无法将interface{}分配给struct。

huangapple go评论88阅读模式
英文:

golang cannot assign interface {} for struct

问题

你好,以下是翻译好的内容:

你好,专家。我正在使用这个库来存储键值对到缓存中:

"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)

这会抛出错误:

在多重赋值中无法将接口{}分配给c(类型为LatestBlockhashCacheResult):需要类型断言

英文:

Hello Expert I'm using this libraray to store K/V in cache

"github.com/bluele/gcache"

The value which I store is this Data Structure

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)

I have no problem with retrieving the cache but not able to Typecast it

c, _ := gc.Get(rf.LastValidBlockHeight)
	fmt.Printf("%T\n", c)

So when i Try this

var c = LatestBlockhashCacheResult{}
	c, _ = gc.Get(rf.LastValidBlockHeight)

This throws me error

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

答案1

得分: 2

你正在尝试将interface{}赋值给一个有类型的变量。为了做到这一点,你需要首先尝试将interface{}值转换为特定的类型。

val, err := gc.Get(rf.LastValidBlockHeight)
if err != nil {
  // 处理错误
}

c, ok := val.(LatestBlockhashCacheResult)
if !ok {
   // val的类型与LatestBlockhashCacheResult不同
}

参考链接:
https://go.dev/tour/methods/15
https://go.dev/tour/methods/16

英文:

You are trying to assign interface{} to a typed variable.
In order to do this you need first try to cast the interface{} value to a specific type

val, err := gc.Get(rf.LastValidBlockHeight)
if err != nil {
  // handle 
}

c, ok := val.(LatestBlockhashCacheResult)
if !ok {
   // val has different type than LatestBlockhashCacheResult
}

Refs:
https://go.dev/tour/methods/15
https://go.dev/tour/methods/16

huangapple
  • 本文由 发表于 2022年2月18日 18:27:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/71171951.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定