我无法以某种方式访问数组中的值。以下是声明数组的方式:
update record1
set id =
(select record2.id
from record2,record1
where record1.name=record2.name
and record1.weight<record2.weight)
但是当我对这个数组进行循环时,我得到空字符串作为值。这就是循环:
messages := strings.Split(request_string, end_of_message_terminator)
这就是输出:
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())
}()
}
有谁知道问题是什么?为什么我可以访问此切片中的各个值?
如果您想运行此代码,以下是整个程序:
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
您需要先运行此程序:
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)
}
}
然后,最后(在启动此程序并运行netcat -l -p 8000
之后),您需要运行:
netcat -l -p 8000
答案 0 :(得分:2)
在你的goroutine中,你没有正确绑定i
:
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
}
您没有看到任何输出,因为每个i
的值都设置为len(messages) - 1
,在这种情况下为2 - 1 = 1
且值为messages[1] == ""
所以每个goroutine都打印messages[1]
这是一个空字符串。