我尝试写简单的计数器,但我不明白他为什么不工作..有我的代码
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
}
有人知道这里有什么问题吗? 谢谢你提前!
答案 0 :(得分:3)
只需更改Jump签名:
Jump(j Count)
您将获得预期的结果。
如果你没有,你会得到:
prog.go:15: invalid operation: *c += j (mismatched types Count and int)
[process exited with non-zero status]