package main
import (
"errors"
"fmt"
)
type FieldElement struct {
Num int
Prime int
}
func (el *FieldElement) Add(o FieldElement) (FieldElement, error) {
if el.Prime != o.Prime {
return FieldElement{}, errors.New("cannot operate on two numbers in different Fields")
}
return FieldElement{(el.Num + o.Num) % el.Prime, el.Prime}, nil
}
// Sub, Mul, Div and Pow also members of FieldElement returning (FieldElement, error)
func main() {
a := FieldElement{13, 19}
b := FieldElement{9, 19}
fmt.Println(a.Add(b))
}
type Point struct {
X FieldElement
Y FieldElement
A FieldElement
B FieldElement
}
现在Point
创建时,我想检查一个点是否在定义为y^2 = x^3 + ax + b
的曲线上
FieldElement的每个操作都返回2个值以满足错误检查。
所以我做不到
x.Pow(3).Add(a.Mul(x)).Add(b)
并以
结束pow3, e1 := x.Pow(three)
mul, e2 := a.Mul(x)
add, e3 := pow3.Add(mul)
rval, e4 := add.Add(b)
// check that y^2 == rval
这使代码难以理解,golang如何正确地执行此操作?
答案 0 :(得分:5)
使您的方法只返回一个值,因此可以将它们链接起来,并将错误值存储在该返回值中,以便进行检查。例如:
type FieldElement struct {
Num int
Prime int
Error error
}
func (el *FieldElement) Add(o FieldElement) *FieldElement {
if el.Error != nil {
// An error already happened, so do nothing
return el
}
if el.Prime != o.Prime {
el.Error = errors.New("cannot operate on two numbers in different Fields")
} else {
el.Num = (el.Num + o.Num) & el.Prime
}
return el
}
然后像这样使用它:
x.Add(...).Mul(...).Sub(...) // etc
if x.Error != nil {
// handle error here
}