Reputation: 395
When I run the following code (it's supposed to reverse the contents of a string), I get strange errors from the compiler.
package main
import "fmt"
func main(){
argString := "I am a string"
arrayPointer := len(argString)
outputString := "string"
for arrayPointer >= 0 ; arrayPointer-- {
outputString := fmt.Sprintf("%s%s", outputString, argString[arrayPointer])
}
}
It throws the following errors:
prog.go:9: syntax error: missing { after for clause
prog.go:12: syntax error: unexpected }
[process exited with non-zero status]
I've used this syntax before (unless I'm missing something), and I've never seen errors from it. What am I missing?
Upvotes: 1
Views: 1586
Reputation: 7948
This code has a few errors besides the malformed for
statement (e.g., your arrayPointer
is initialized to len(argString)
rather than len(argString)-1
, so you'll hit an out-of-bounds violation right away).
Anyway, I think this an optimized, idiomatic version of what you're attempting:
http://play.golang.org/p/fFCf3L8ov9
package main
import "fmt"
func main() {
inString := "I am a string"
// use an output buffer because (1) strings are immutable and
// (2) appending to strings creates a new string from the existing
// string and its new appendix. This method allocates
// all the necessary memory 1 time. len(inString) allocations
// vs 1 allocation.
outBuffer := make([]uint8, len(inString))
for i := 0; i < len(outBuffer); i++ {
// copy the i-th character from the end of the string
// into the i-th position of outBuffer
outBuffer[i] = inString[len(inString)-i-1]
}
fmt.Println(string(outBuffer))
}
Upvotes: 1
Reputation: 43949
From the spec, there are three forms for a for
statement:
Your statement doesn't match any of these. Most likely the compiler has decided that you are using (1), and errors out when there isn't a {
after arrayPointer >= 0
. You can fix this by changing to case (2):
for ; arrayPointer >= 0 ; arrayPointer-- {
(or using the arrayPointer
initialisation statement as the first part of the for
statement).
Upvotes: 6