doubingjian2006 2019-03-01 15:31
浏览 245

我在Golang中正确使用重命名的类型吗?

I have to deal with huge integers in Golang that come in from a Swagger-defined REST API. Since Swagger needs a Validate(strfmt.Registry), I define my custom type like this:

// BigInt is a big.Int, but includes a Validate() method for swagger
// Once created, it can be used just like a big.Int.
type BigInt struct {
    *big.Int
}

Since it needs to be transformed to and from JSON, I define some JSON Marshaling interface:

// UnmarshalJSON implements encoding/json/RawMessage.UnmarshalJSON
func (b *BigInt) UnmarshalJSON(data []byte) error {
    err := json.Unmarshal(data, &b.Int)
    if err != nil {
        return err
    }

    return nil
}

// MarshalJSON calls json.Marshal() on the BigInt.Int field.
func (b *BigInt) MarshalJSON() ([]byte, error) {
    if b == nil {
        return []byte("null"), nil
    }
    return json.Marshal(b.Int)
}

Now I realized that my custom type doesn't actually behave exactly like big.Int. In order to compare two BigInts:

example := BigInt{Int: &big.Int{}}
other := BigInt{Int: &big.Int{}}
example.Cmp(other.Int)

I cannot do

example.Cmp(other)

which is much cleaner. And creating the BigInt is also a terrible experience, which I have to wrap in a function like this:

// NewBigInt creates a BigInt with its Int struct field 
func NewBigInt() (i *BigInt) {
    return &BigInt{Int: &big.Int{}}
}
  1. Is this really how I'm supposed to do things?
  2. Why can't golang treat big.Int just like its other built in types like int64/uint64/float64?
  • 写回答

1条回答 默认 最新

  • doushe2513 2019-03-01 15:42
    关注

    Is this really how I'm supposed to do things?

    It's a way to do it, but it's not what I'd call a "renamed" type; it's a struct containing a single field. You could also do (like, for example, time.Duration):

    type BigInt *big.Int
    

    And apply methods to it. This would allow you to seamlessly convert between *big.Int and your type.

    Why can't golang treat big.Int just like its other built in types like int64/uint64/float64?

    Because unlike those types, big.Int isn't a built-in type; you can tell because it's big.Int, i.e., it's defined in a package, not in the language.

    评论

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上