dsgd4654674 2019-06-03 14:42 采纳率: 0%
浏览 34

为big.Int创建类型别名-但我无法使用其指针接收器设置它?

I thought a type alias would be more elegant than embedding a struct. You see, if I create a new type BigInt that embeds big.Int, I'd have to take care that the embedded big.Int is initialized at all times, and unless I reimplement big.Int's like Cmp, Add, Sub, all the code that depends on this new type needs to know that BigInt's methods actually receive a big.Int for their arguments. Which is stupid.

So I tried aliasing a type.

type BigInt big.Int

// String casts BigInt into big.Int and uses its String method.
func (b *BigInt) String() string {
    bc := big.Int(*b)
    return bc.String()
}

But Setting the pointer receiver is now very tricky because I don't have access to the internals of big.Int. This following code doesn't work at all:

// UnmarshalJSON casts BigInt into big.Int and uses its UnmarshalJSON method.
func (b *BigInt) UnmarshalJSON(text []byte) error {
    bc := new(big.Int)
    err := bc.UnmarshalJSON(text)
    if err != nil {
        return err
    }
    b = b.Set(bc)
    return nil
}

// Set is different from big.Int.Set() in that you must use the value it returns
func (b *BigInt) Set(i *big.Int) *BigInt {
    iB := BigInt(*i)
    b = &iB
    return b
}

What can I do?

  • 写回答

2条回答 默认 最新

  • dousi9215 2019-06-03 14:46
    关注

    That isn't a type alias, it's a new type, and therefor has none of the methods of the underlying big.Int type. A type alias would be type BigInt = big.Int, but then you couldn't define new methods on it. A type's methods are locked to its package: there is no way to define methods on an imported type in addition to the methods it already has defined. Embedding is the closest you're likely to get to that. More likely you want to reconsider your design, most likely by creating functions that take a big.Int instead of trying to define new methods.

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100