登录
首页 >  Golang >  Go问答

结构不是类型:当被传递给单独包中函数作为参数

来源:stackoverflow

时间:2024-03-03 11:36:24 416浏览 收藏

本篇文章向大家介绍《结构不是类型:当被传递给单独包中函数作为参数》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

我正在制作一个 json 验证函数并尝试实现它。但是,当我尝试将结构作为参数导入到位于另一个包中的验证函数时,我的结构出现了问题。

它位于另一个包中的原因是因为我将在不同的路由文件中调用通用验证函数,所以我实际上不能在该包中包含任何结构,它们必须在路由文件中导入和定义。

type usersjson struct {
    users struct {
        put []userjson `json:"put"`
    } `json:"users"`
}

type userjson struct {
    display_name     string `json:"display_name"`
    username        string `json:"username"`
    email           string `json:"email"`
    password        string `json:"password"`
}

func myfunc(w http.responsewriter, r *http.request) {
    errors, _ := schema.validate(data, r, usersjson)
}

func validate(schemahelper interface{}) (interface{}, error) {
    file, err := os.open("config/schema/schema.json")
    if err != nil {
        return nil, err
    }

    defer file.close()

    bytevalue, _ := ioutil.readall(file)

    var helpers schemahelper // this is the error

    json.unmarshal(bytevalue, &helpers)
    fmt.printf("%v", helpers)
}

我的 json 架构如下所示:

{
    "users": {
        "PUT": {
        }
    }
}

我想让这个方法发挥作用,因为它使自动化验证变得更加容易和更快。

这不会编译并给出错误 schemahelper 不是类型

知道如何解决这个问题吗?


解决方案


您正在尝试声明一个名为 helpers 的变量,其类型为 schemahelper,但是(至少在所示的代码中)您尚未定义任何名为 schemahelper 的类型。您有一个名为 schemahelper变量。您不能将类型用作变量,也不能将变量用作类型。您必须通过传递 usersjson实例来调用 validate,然后您可以直接将 json 解组到其中。看来您可能正在寻找的是这样的东西:

func MyFunc(w http.ResponseWriter, r *http.Request) {
    var unmarshaled UsersJSON
    errors, _ := schema.Validate(&unmarshaled)
}

func Validate(schemaHelper interface{}) (error) {
    file, err := os.Open("config/schema/schema.json")
    if err != nil {
        return nil, err
    }

    defer file.Close()

    byteValue, _ := ioutil.ReadAll(file)

    return json.Unmarshal(byteValue, schemaHelper)
}

这会将 json 解组到变量 schemahelper (无论它是什么类型),以便调用者按照其认为合适的方式使用。请注意,这是一个粗略的最佳猜测,因为在您的问题中,对 validate 的调用传递了 3 个参数,但给出的函数定义仅接受 1 个参数。

但是,我认为这不会像您根据问题所认为的那样进行“验证”。它仅验证 json 语法上有效,而不是验证它与您传入的 struct 有任何关系 - 它可能具有结构中未定义的字段,也可能缺少以下字段已定义,并且不会返回任何错误。

最后,类型 usersjson 没有导出字段(所有字段都以小写字母开头,使它们成为未导出/私有的),因此无论如何都不会将任何内容解组到其中。 encoding/json 只能解组到导出字段中。

您收到此错误是因为 schemahelper 不是类型。事实上,它是 interface{} 类型的函数变量,正如您在函数 validate 中声明的那样。

好了,本文到此结束,带大家了解了《结构不是类型:当被传递给单独包中函数作为参数》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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