【发布时间】:2017-07-20 20:24:52
【问题描述】:
我制作了一个接口,用于对结构值进行基本数学运算。接口的数学函数总是更新结构指针的值。
我的问题是,在某些时候,我想将值覆盖为初始值,但我只有接口可以使用。因为它是一个指针接口(不是 100% 确定这是否是人们所说的),所以我无法“克隆”结构的初始值以便以后覆盖。
还请注意,我正在尽力避免反思。
这是我的代码。可能比我试图解释它更有意义:
package main
import (
"fmt"
)
type mather interface {
add(mather) mather
sub(mather) mather
}
type float struct {
value float64
}
func (f *float) add(m mather) mather {
f.value += m.(*float).value
return f
}
func (f *float) sub(m mather) mather {
f.value -= m.(*float).value
return f
}
func (f *float) get() interface{} {
return *f
}
func main() {
var a, b, c mather
a = &float{2} // this could be any time. approximitly 10 possible types
b = &float{7} // this could be any time. approximitly 10 possible types
// float can't be used again below, only mather
c = a
fmt.Println(a)
fmt.Println(b)
fmt.Println()
// a's math
doMath(a)
// now math is done, we need to reset the value from before the math was done
// set *a equal to *c. (a == &float{2})
resetMath(a, c)
// b's math
doMath(b)
// now math is done, we need to reset the value from before the math was done
// set *b equal to *c. (b == &float{7})
resetMath(b, c)
fmt.Println(a)
fmt.Println(b)
}
func doMath(m mather) {
m.add(&float{3})
}
func resetMath(m mather, r mather) {
m = r
}
【问题讨论】:
-
预期输出是多少?
6?接口是一种契约,与底层数据的交互(可以是指针、值、任何你喜欢的……)应该通过方法集来完成。所以,如果你想获取接口的克隆,应该提供一种clone() mather方法。要修改界面,应该通过其他方法来完成,例如set(mather),那么底层数据的修改应该在这个set方法中完成(你可以使用类型断言等......)。 -
@putu yip 预期的输出应该是 6。我认为应该进行设置和克隆方法,但我正在努力定义这些返回
mather接口的方法。
标签: pointers go struct interface