登录
首页 >  Golang >  Go问答

无法同时使用函数和 if else 语句

来源:stackoverflow

时间:2024-02-24 14:45:27 208浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《无法同时使用函数和 if else 语句》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我正在尝试使用 go 构建一个基本的缓存系统作为教程。

出于某种原因,当我运行此命令时,if else 语句会导致错误。

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
}

我做错了什么?我试图输入一个密钥,然后从缓存或数据库返回值。不确定我的语法做错了什么!


解决方案


go 条件语句遵循以下语法

if something{
      ......

   } else if something{
      ......

   } else{
      ......
   }

a detailed answer

好了,本文到此结束,带大家了解了《无法同时使用函数和 if else 语句》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>