为什么通过方法传递函数参数时计数器不增加

huangapple go评论119阅读模式
英文:

Why counter not increase on function argument via method

问题

我尝试编写一个简单的计数器,但我不明白为什么它不起作用。这是我的代码:

  1. package main
  2. import "fmt"
  3. type Count int
  4. type Counter interface {
  5. Next()
  6. Prev()
  7. Jump(j int) //我想将Count增加到'j'的值
  8. }
  9. func (c *Count) Next() { *c += 1 }
  10. func (c *Count) Prev() { *c -= 1 }
  11. func (c *Count) Jump(j int) { *c += j } //这里有错误
  12. func main() {
  13. val := new(Count) //0
  14. val.Next() //+1
  15. val.Jump(4) //+4
  16. val.Prev() //-1
  17. fmt.Println("现在是", *val) //期望输出4
  18. }

有人知道这里的问题吗?提前感谢!

英文:

I try writing simple counter but I don't understand why he didn't work.. There is my code

  1. package main
  2. import "fmt"
  3. type Count int
  4. type Counter interface {
  5. Next()
  6. Prev()
  7. Jump(j int) //i want increase Count to 'j' value
  8. }
  9. func (c *Count) Next() { *c += 1 }
  10. func (c *Count) Prev() { *c -= 1 }
  11. func (c *Count) Jump(j int) { *c += j } //Here Error
  12. func main() {
  13. val := new(Count) //0
  14. val.Next() //+1
  15. val.Jump(4) //+4
  16. val.Prev() //-1
  17. fmt.Println("Now ", *val) //expected 4
  18. }

Is anybody knows what the problem here?
Thanks for advance!

答案1

得分: 3

只需简单更改Jump函数的签名:

  1. Jump(j Count)

然后你将得到预期的结果。

请参考kbd

如果不更改,你将得到以下错误信息:

  1. prog.go:15: invalid operation: *c += j (mismatched types Count and int)
  2. [process exited with non-zero status]
英文:

Simply change the Jump signature:

  1. Jump(j Count)

And you will get the expected result.

See <kbd>play.golang.org</kbd>

If you don't, you would get:

  1. prog.go:15: invalid operation: *c += j (mismatched types Count and int)
  2. [process exited with non-zero status]

huangapple
  • 本文由 发表于 2014年10月19日 00:57:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/26442279.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定