我尝试编写简单的计数器,但我不明白为什么他不工作。这是我的代码
package main
import "fmt"
type Count int
type Counter interface {
Next()
Prev()
Jump(j int) //i want increase Count to 'j' value
}
func (c *Count) Next() { *c += 1 }
func (c *Count) Prev() { *c -= 1 }
func (c *Count) Jump(j int) { *c += j } //Here Error
func main() {
val := new(Count) //0
val.Next() //+1
val.Jump(4) //+4
val.Prev() //-1
fmt.Println("Now ", *val) //expected 4
}
有人知道这里的问题是什么吗? 感谢您的提前!
最佳答案
只需更改跳转签名:
Jump(j Count)
你会得到预期的结果。
如果你不这样做,你会得到:
prog.go:15: invalid operation: *c += j (mismatched types Count and int)
[process exited with non-zero status]
关于go - 为什么计数器不通过方法增加函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26442279/