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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭