go - func 的语法 Golang 错误

标签 go

为什么下面的代码会抛出意外的函数错误?我看到错误 ./func_correct.go:4: syntax error: unexpected func, expecting name

package main

func (st  *Stack)  Pop() int {
        v := 0
        for ix := len (st) - 1; ix >= 0; ix-- {
                if v = st[ix]; v != 0 {
                    st[ix] = 0
                    return v
                }
        }
        return 0
}

func main() {
   Pop()    
}

最佳答案

  1. 定义堆栈类型

  2. main 中为其创建一个变量

  3. 对其调用Pop

代码:

package main

import "fmt"

type Stack []int

func (st Stack) Pop() int {
    v := 0
    for ix := len(st) - 1; ix >= 0; ix-- {
        if v = st[ix]; v != 0 {
            st[ix] = 0
            return v
        }
    }
    return 0
}

func main() {
    s := Stack{1, 2, 3, 4}
    i := s.Pop()
    fmt.Println(i)
}

https://play.golang.org/p/PSac-C0xJM

关于go - func 的语法 Golang 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46763057/

相关文章:

go - 解析文件,忽略注释和空行

go - Go channel 上的范围循环和循环变量的垃圾回收

go - 无法使用vscode解析自己定义的golang软件包

go - 如何为 Go 中的行插入重用单个 Postgres DB 连接?

json - Golang 解码 json 映射和数组

GORM 不忽略 `gorm:"-"` 字段

golang : can't execute t. 执行

unit-testing - Google App Engine 数据存储 - 测试查询失败

go - 在匿名结构中初始化一个字段

performance - 子集 DataFrames 时的 Goroutines 开销和性能分析(Gota)