gpt4 book ai didi

go - 我是否在 Golang 中正确使用重命名的类型?

转载 作者:IT王子 更新时间:2023-10-29 02:00:55 26 4
gpt4 key购买 nike

我必须在 Golang 中处理来自 Swagger 定义的 REST API 的巨大整数。由于 Swagger 需要 Validate(strfmt.Registry),因此我定义自定义类型如下:

// 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
}

由于需要与JSON相互转换,我定义了一些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)
}

现在我意识到我的自定义类型实际上并不完全像 big.Int。为了比较两个 BigInt:

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

我做不到

example.Cmp(other)

这样干净多了。创建 BigInt 也是一种糟糕的体验,我必须将其包装在这样的函数中:

// NewBigInt creates a BigInt with its Int struct field 
func NewBigInt() (i *BigInt) {
return &BigInt{Int: &big.Int{}}
}
  1. 这真的是我应该做的事情吗?
  2. 为什么 golang 不能像处理其他内置类型(如 int64/uint64/float64)一样处理 big.Int?

最佳答案

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

这是一种的方式,但它不是我所说的“重命名”类型;它是一个包含单个字段的结构。您也可以这样做(例如 time.Duration ):

type BigInt *big.Int

并对其应用方法。这将允许您在 *big.Int 和您的类型之间无缝转换。

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

因为与那些类型不同,big.Int 不是内置类型;你可以分辨出来,因为它是 big.Int,也就是说,它是在包中定义的,而不是在语言中定义的。

关于go - 我是否在 Golang 中正确使用重命名的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54947732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com