英文:
Why counter not increase on function argument via method
问题
我尝试编写一个简单的计数器,但我不明白为什么它不起作用。这是我的代码:
package main
import "fmt"
type Count int
type Counter interface {
Next()
Prev()
Jump(j int) //我想将Count增加到'j'的值
}
func (c *Count) Next() { *c += 1 }
func (c *Count) Prev() { *c -= 1 }
func (c *Count) Jump(j int) { *c += j } //这里有错误
func main() {
val := new(Count) //0
val.Next() //+1
val.Jump(4) //+4
val.Prev() //-1
fmt.Println("现在是", *val) //期望输出4
}
有人知道这里的问题吗?提前感谢!
英文:
I try writing simple counter but I don't understand why he didn't work.. There is my code
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
}
Is anybody knows what the problem here?
Thanks for advance!
答案1
得分: 3
只需简单更改Jump函数的签名:
Jump(j Count)
然后你将得到预期的结果。
请参考kbd。
如果不更改,你将得到以下错误信息:
prog.go:15: invalid operation: *c += j (mismatched types Count and int)
[process exited with non-zero status]
英文:
Simply change the Jump signature:
Jump(j Count)
And you will get the expected result.
See <kbd>play.golang.org</kbd>
If you don't, you would get:
prog.go:15: invalid operation: *c += j (mismatched types Count and int)
[process exited with non-zero status]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论