繁体   English   中英

如何从不同的包调用 Golang 中的方法

[英]How to call a method in Golang from a different package

我的 errors.go 文件

 package errors

import (
    "net/http"
)

type RestError struct {
    Message string `json:"message"`
    Status  int    `json:"status"`
    Error   string `json:"error"`
}

func (err *RestError) NewBadRequestError(message string) {
    err.Message = message
    err.Status = http.StatusBadRequest
    err.Error = "bad_request"
}

我的 user.go 文件

 package users

import (
    errors "Utils/Errors"
)

type (
    User struct {
        ID       uint   `json:"id"`
        Name     string `json:"name"`
        LastName string `json:"last_name"`
        Email    string `json:"email"`
    }
)

func (u *User) Validate() (err *errors.RestError) {

    if u.Name == "" {
        return &err.NewBadRequestError("The name field can't be empty")
    }

    return nil
}

我总是收到以下编译器错误

err.NewBadRequestError(*message) (no value) used as valuecompiler

想知道我做错了什么。 我也试过 return &err.NewBadRequestError(message: "The name field can't be empty") 但仍然得到以下语法错误:在参数列表语法中缺少','

您的问题与单独的包无关。

首先, err没有定义。 我假设您在粘贴的代码中未显示的地方定义了它。 如果这是准确的...

return &err.NewBadRequestError("The name field can't be empty")

没有任何意义。

首先, err.NewBadRequestError()不返回任何东西,所以没有什么可返回的。

其次,你有一个& ,这意味着获取值的地址,但同样,没有值——这就是错误告诉你的。

目前尚不清楚您的代码打算做什么,因此我无法确切地告诉您如何修复它。 一种选择是从您的代码中删除return &

    if u.Name == "" {
        err.NewBadRequestError("The name field can't be empty")
    }

另一种方法是修改NewBadRequestError以返回一些值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM