dqyp50298 2018-06-12 21:30
浏览 41
已采纳

如何禁用常量的隐式类型转换? [重复]

This question already has an answer here:

I have the following code snippent:

type ErrorCode string

const (
    INVALID_REQUEST ErrorCode = "INVALID_REQUEST"
)

type Response struct {
    ErrorCode string `json:"errorCode"`
}

func BuildResponseError(errorCode ErrorCode) string {
    user := &Response{ErrorCode: string(errorCode)}
    response, err := json.Marshal(user)
    if err != nil {
        log.Println(err)
        return `{"errorCode":"bad_request"}`
    }

    return string(response)
}

I can call function BuildResponseError like that:

BuildResponseError("wrong_request")

Is there a way to disable this implicit type conversion? I want to call this function only like this, using a enum value:

BuildResponseError(INVALID_REQUEST)
</div>
  • 写回答

1条回答 默认 最新

  • dongyi9330 2018-06-12 21:54
    关注

    You can't disable the possibility to assign a string to a variable of your ErrorCode type since ErrorCode's underlying type is string and according to Go's assignability rules:

    A value x is assignable to a variable of type T ("x is assignable to T") if one of the following conditions applies:

    ...

    • x's type V and T have identical underlying types and at least one of V or T is not a defined type

    Source: https://golang.org/ref/spec#Assignability

    So that functionality is built-in into the language.

    One way to achieve similar functionality (not exactly the same but the closest you can get) would be to define the type like:

    type ErrorCode struct {
        Code string
    }
    

    And then a variable (you can't define a constant of that type):

    var (
        INVALID_REQUEST ErrorCode = ErrorCode{"INVALID_REQUEST"}
    )
    

    You should then modify your code, of course, to take the Code from inside that type to build the response:

    user := &Response{ErrorCode: errorCode.Code}
    

    That way the function can't be called using a string, only ErrorCode values will be accepted.

    Playground: https://play.golang.org/p/qoKrGiJQtxv

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥15 this signal is connected to multiple drivers怎么解决
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus