GO中函数体错误之外的非声明语句

我是 Go 的新手,这些问题让我很困惑。我无法解决它们,你们能帮我吗?


func Solution(A []int, B[]int, K int) int{

.......

res = MaxInt32 

low = 0

high = Min(900, largestId) //largestId is limited here

mid = 0


while(low <= high){

    mid = {low + high} / 2         55

    if(isAvailable(K, mid)){

        res := Min(res, mid)

        high :=mid - 1

    } else{

        low := mid + 1

    }


}

return res                         64

}                                  65

错误显示:


workspace/src/solution/solution.go:55: syntax error: unexpected =, expecting }

workspace/src/solution/solution.go:64: non-declaration statement outside function body

workspace/src/solution/solution.go:65: syntax error: unexpected }

我不明白为什么会出现这些问题?


白衣非少年
浏览 334回答 2
2回答

慕娘9325324

whileGo 中没有循环。只有for。如果我这样做:package mainfunc main() {&nbsp; &nbsp; var n int&nbsp; &nbsp; while (n < 10) {&nbsp; &nbsp; &nbsp; &nbsp; n++&nbsp; &nbsp; }&nbsp; &nbsp; return}我收到以下错误(与您的类似):untitled 3:6: syntax error: unexpected ++, expecting }untitled 3:8: non-declaration statement outside function bodyuntitled 3:9: syntax error: unexpected }如果我这样做while n < 10(没有括号),我会得到更精确的消息,即第 5 行 ( )出现意外的名称错误while。我相信由于括号的使用,编译器将(非保留字)while视为一种类型(函数调用或类型转换),但在意识到它不存在之前,还有其他错误需要报告。因此,也许对您来说是一个令人困惑的消息。除非您的代码中有其他错误,否则重命名while为for应该可以工作。并去掉括号。

眼眸繁星

例如,package mainimport (&nbsp; &nbsp; "math")func Min(a, b int) int {&nbsp; &nbsp; if a > b {&nbsp; &nbsp; &nbsp; &nbsp; return b&nbsp; &nbsp; }&nbsp; &nbsp; return a}func isAvailable(k, mid int) bool {&nbsp; &nbsp; // ...&nbsp; &nbsp; return true}func Solution(A []int, B []int, K int) int {&nbsp; &nbsp; largestId := 0&nbsp; &nbsp; // ...&nbsp; &nbsp; res := math.MaxInt32&nbsp; &nbsp; low := 0&nbsp; &nbsp; high := Min(900, largestId)&nbsp; &nbsp; for low <= high {&nbsp; &nbsp; &nbsp; &nbsp; mid := (low + high) / 2&nbsp; &nbsp; &nbsp; &nbsp; if isAvailable(K, mid) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res = Min(res, mid)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; high = mid - 1&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; low = mid + 1&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return res}func main() {}你需要学习基本的 Go 语法。参加Go Tour。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go