Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

golang cannot assign interface {} for struct

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading