La fonction ne fonctionnera pas avec les instructions if else [duplicate]

Jan 15 2021

J'essaie de créer un système de cache de base avec Go comme didacticiel.

Pour une raison quelconque, lorsque j'exécute ceci, l'instruction if else conduit à une erreur.

package datasource

import (
    "fmt"
    "github.com/patrickmn/go-cache"
    "time"
)

type DataSource interface {
    Value(key string) (interface{}, error)

}

// DataSourceStr type, implements the DataSource interface
type DataSourceStr struct {
    data map[string]string
}


var cache = cache.New(5*time.Minute, 5*time.Minute)


func (n *DataSourceStr) Value(key string) (interface{}, error) {
        /* 
    1. Compute a cache key
    2. Search cache key
    3. If hit return value
    4. If miss, do datasource
    5. Cache and return slow thing.
    */
    
    cached, found := cache.Value(key)
    if found {
        return cached, nil
    }

    else if _, ok := n.data[key]; ok 
    {
        //measure how often a key gets called.
        cache.Set(key, n.data[key], cache.DefaultExpiration)
        return n.data[key], nil
    } else {
        return nil, fmt.Errorf("key not found %v", ok)
    }
}




func getFromDS(datasource DataSource, key string) (string, error) {

    
    v, err := datasource.Value(key)
    
    //create a map that decays based on time.

    if err != nil {
        return "", nil
    }

    return fmt.Sprint(v), nil
}

Qu'est-ce que je fais mal? J'essaie de faire entrer une clé, puis je renvoie la valeur du cache ou de la base de données. Je ne sais pas ce que j'ai fait de mal avec la syntaxe!

Réponses

1 heheh Jan 15 2021 at 14:39

go les instructions conditionnelles suivent la syntaxe suivante

   if something{
      ......

   } else if something{
      ......

   } else{
      ......
   }

une réponse détaillée