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

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

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]

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:

确定