go - 为什么计数器不通过方法增加函数参数

标签 go

我尝试编写简单的计数器,但我不明白为什么他不工作。这是我的代码

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)

你会得到预期的结果。

参见 play.golang.org

如果你不这样做,你会得到:

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/

相关文章:

go - 为什么运行“go test”仅在我的main_test.go文件中运行测试?

gomodule/redigo 如何将多个 key 推送到 redis

git - 在每次提交时分别运行 go fmt 时,是否有任何工具会重新设置 Git 中的分支?

Go最佳实践: function vs method with ambiguous receiver?

go - 如何在模板中转换给定的代码

parameters - 戈朗 : get not named params

go - 将数据发布到端点后请求正文为空

syntax - 在go中,为什么是[]int而不是int[]?

testing - Go包之间如何共享测试接口(interface)?

go - 打断休眠的 goroutine?