0

I can't access the values in an array somehow. Here is how the array is declared:

messages := strings.Split(request_string, end_of_message_terminator)

But when I make a loop over this array, I get empty strings as values. That's the loop:

for i, v := range messages {
    fmt.Printf("messages are (3) %q\n", messages)
    go func(){

        fmt.Printf("message is %s\n", messages[i])
        fmt.Printf("i is %s\n", i)
        fmt.Printf("v is %s\n", v)
        respond_to_message(messages[i], response_writer())
    }()


}

And that's the output:

messages are (3) ["asti" ""]
messages are (3) ["asti" ""]
message is                  
i is %!s(int=1)             
v is                        
message is                  
i is %!s(int=1)             
v is               

Does anyone know what the problem is? Why can I access the individual values in this slice?

Just in case you want to run this code, here is the entire program:

package main


import (
    "fmt"
    "net"
    "os"
    "strings"
//  "io/ioutil"


)


func main() {

    end_of_message_terminator := "||"
    beginning_of_next_message := ""
    request := make([]byte, 512)

    service_port := ":7777"
    tcpAddr, err := net.ResolveTCPAddr("tcp4", service_port)
    checkError(err)
    listener, err := net.ListenTCP("tcp", tcpAddr)
    checkError(err)



    for {
        conn, err := listener.Accept()

        if err != nil {

            continue

        }

        read_len, err := conn.Read(request)

        if read_len == 0 {
            continue
        }

        request_string := string(request[:read_len])
        fmt.Printf("Request String '%s'\n", request_string)

        messages := strings.Split(request_string, end_of_message_terminator)
        fmt.Printf("messages are (1) %q\n", messages)

        messages[0] = beginning_of_next_message + messages[0]

        if messages[len(messages) - 1] != "" {
            beginning_of_next_message = messages[len(messages) - 1]
            messages[len(messages) - 1] = ""

        }

        if len(messages) == 1 {
            continue
        }

        fmt.Printf("messages are (2) %q\n", messages)
        for i, v := range messages {
            fmt.Printf("messages are (3) %q\n", messages)
            go func(){

                fmt.Printf("message is %s\n", messages[i])
                fmt.Printf("i is %s\n", i)
                fmt.Printf("v is %s\n", v)

            }()


        }
        conn.Close()

    }

}






func checkError(err error) {

    if err != nil {

        fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
        os.Exit(1)

    }

}

You need to run this program first:

netcat -l -p 8000

And then, finally (after starting both this program and running netcat -l -p 8000) you need to run:

printf "asti||"  | netcat localhost 7777
2

1 Answer 1

2

In your goroutine you are not binding i properly:

for i, v := range messages {
    fmt.Printf("messages are (3) %q\n", messages)
    go func(i int){

        fmt.Printf("message is %s\n", messages[i])
        fmt.Printf("i is %s\n", i)
        fmt.Printf("v is %s\n", v)
        respond_to_message(messages[i], response_writer())
    }(i) // you'll have to pass i here
}

You don't see any output because for each the value of i gets set to len(messages) - 1 which in this case is 2 - 1 = 1 and the value messages[1] == ""

So each goroutine is printing messages[1] which is an empty string.

Sign up to request clarification or add additional context in comments.

1 Comment

Right answer but wrong reason - it's not that i is set to len(messages) - 1. It's because when you queue up all the goroutines closed over i, if they don't run until the loop finishes, then i still the value from the last iteration of the loop. If you removed the go (so that the closures ran immediately) you'd find the expected behavior, but no concurrency.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.