代码之家  ›  专栏  ›  技术社区  ›  P. Nick

当作为参数传递给单独包中的函数时,Struct不是类型

go
  •  -1
  • P. Nick  · 技术社区  · 6 年前

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

    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 is not a type

    知道我怎么解决这个问题吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Adrian    6 年前

    您试图声明一个名为 helpers ,类型 schemaHelper schemaHelper公司 . 你有一个 变量 打电话 . 不能将类型用作变量,也不能将变量用作类型。你得打电话 Validate 通过一个 实例 属于 UsersJSON

    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公司 (无论是哪种类型),以便调用者根据需要使用。请注意,这是一个粗略的最佳猜测,因为在您的问题中 验证

    然而,我不认为这是“验证”的方式,你认为它是基于问题。它只验证JSON是 句法有效 ,并不是说它与 struct 您传入-它可能有未在结构中定义的字段,可能缺少已定义的字段,并且不会返回任何错误。

    最后,类型 没有导出字段(所有字段都以小写字母开头,使其成为未报告/私有字段),因此无论发生什么,都不会对其进行解组。 encoding/json 只能解组到导出字段。

        2
  •  0
  •   shaq    6 年前

    你得到这个错误是因为 schemaHelper interface{} ,正如您在函数中声明的那样 Validate .