1
votes

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?

2
I don't know Go, but looks to me like you are missing an initializer on that for loop... e.g. arrayPointer := len(argString);John3136
Guessing you were writing it as an exercise; either way, using an array slice makes sense when you may need to change a string character-by-character: play.golang.org/p/XOlnr7KP2Y . Strings in Go are immutable, so you can't just append a character to one. Instead, you're allocating a new string each pass through your loop.twotwotwo

2 Answers

6
votes

From the spec, there are three forms for a for statement:

  1. a single conditional expression
  2. the three statement version giving an init statement, condition and post statement
  3. a range clause.

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).

1
votes

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))
}