Reputation: 67
I am a new learner with Go, and these problems confused me a lot. I cannot solve them, could you guys give me a hand?
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
The errors show:
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 }
I don't understand why these problems come?
Upvotes: 0
Views: 2792
Reputation: 13062
There's no while
loop in Go. Only for
. If I do this:
package main
func main() {
var n int
while (n < 10) {
n++
}
return
}
I get the following error (similar to yours):
untitled 3:6: syntax error: unexpected ++, expecting }
untitled 3:8: non-declaration statement outside function body
untitled 3:9: syntax error: unexpected }
If I do while n < 10
(no parentheses) I get more precise message, i.e. an unexpected name error on line 5 (while
). I believe due to a bracket usage compiler treats (non-reserved word) while
as a type (function call or type conversion), but before realising it's non-existent there are other errors to report. Hence, maybe, a confusing message for you.
Unless you have other errors in your code, renaming while
to for
should work. And drop the brackets.
Upvotes: 2
Reputation: 166569
For example,
package main
import (
"math"
)
func Min(a, b int) int {
if a > b {
return b
}
return a
}
func isAvailable(k, mid int) bool {
// ...
return true
}
func Solution(A []int, B []int, K int) int {
largestId := 0
// ...
res := math.MaxInt32
low := 0
high := Min(900, largestId)
for low <= high {
mid := (low + high) / 2
if isAvailable(K, mid) {
res = Min(res, mid)
high = mid - 1
} else {
low = mid + 1
}
}
return res
}
func main() {}
You need to learn basic Go syntax. Take the Go Tour.
Upvotes: 0