登录
首页 >  Golang >  Go问答

如何在Golang中编写条件语句?

来源:stackoverflow

时间:2024-03-05 18:36:27 212浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《如何在Golang中编写条件语句?》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我在控制器部分编写查询,但根据 mvc 结构,逻辑位于模型中,控制器部分仅用于发送数据,所以过去我使用如下条件:-

models.retrieve(bson.m{"_id": id, "is_deleted": false})

//fucntion for this query is 
fucn retrieve(query interface{}){

    // do stuff

}

但是现在上面的查询将使用映射进行更改,我正在编写一个函数以将其用于检索数据的多种目的,例如:-

conditions := make(map[string]interface{})
conditions["operator1"] = "_id"
codnitions["value1"] = id
conditions["operator2"] = "is_deleted"
conditions["value2"] = false

func retrieve(data map[string]interface{}){

//queries here

}

有人告诉我这是正确的方法。如果是,请告诉我怎么做?

如果不是,您能否告诉我一个例子或适合我的问题的答案。

已编辑:-

该函数也用于通过“代码”方式查找​​ models.retrieve(bson.m{"code": code, "is_deleted": false})

也可以这样写:-

conditions := make(map[string]interface{})
conditions["operator1"] = "code"
codnitions["value1"] = Code
conditions["operator2"] = "is_deleted"
conditions["value2"] = false

提前谢谢您。


解决方案


如果我理解正确,您需要一个能够处理不同键值对作为查询输入的函数。我在 go 中实现如下:

type userresolver int

// string satisfies the stringer interface
func (ur userresolver) string() string {
    strs := [...]string {
        "id",
        "code",
    }
    // return empty string if index out of bounds
    if int(ur) >= len(strs) {
        return ""
    }
    return strs[ur]
}

// add any required functions to userresolver that you may require,
// such as schemakey() that returns the specified schema key value:
// in your example case "_id", "code", "is_deleted", etc.

const (
    id userresolver = iota
    code
)

func resolveuser(by userresolver, value interface{}) (user, error) {
    if by.string() == "" {
        return nil, fmt.errorf("unknown userresolver specified")
    }

    if value == nil {
        return nil, fmt.errorf("nil value provided, unable to resolve user")
    }

    // query details here:
    // it will be specific to your persistence model and remember to follow the
    // best practices for your specific db, such as properly escaping inputs...

    return user, nil
}

这种方法通过使用可以导出或不导出的附加函数(根据您的 api 设计)扩展 userresolver 功能,为您提供了极大的灵活性。它基本上将各种选项映射到具有公共索引的切片中,如使用 iota (自动枚举)在 const 部分中定义的那样。您现在可以添加使用 switch 语句来执行类型或条件特定工作的函数。

该函数现在可以由其他包调用,如下所示:

u, err := ResolveUser(user.ID, uid)
if err != nil {
    return fmt.Errorf(
        "User not found! Unable to obtain user by %s = %v",
        user.ID,
        uid,
    )
}

条件部分可以类似地实现,然后正确区分查找索引和查找条件。

本篇关于《如何在Golang中编写条件语句?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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