语法错误:意外名称,期望分号或换行符

时间:2015-07-14 15:54:08

标签: go

我不明白为什么我的代码有语法错误。

package main

import (
    "fmt"
    "os/exec"
    "time"
)

func ping(curl_out string) endtime int64 {
    try_curl := exec.Command("curl", "localhost:8500/v1/catalog/nodes")
    try_curl_out := try_curl.Output()
    for try_curl_out == curl_out {
        try_curl := exec.Command("curl", "localhost:8500/v1/catalog/nodes")
        try_curl_out := try_curl.Output()
    }
    endtime := time.Now().Unix()
    return endtime
}

func main() {
    run_container := exec.Command("docker", "run", "-p", "8400:8400", "-p", "8500:8500", "-p", "8600:53/udp", "-h", "node1", "progrium/consul", "-server", "-bootstrap")
    container_id, err := run_container.Output()
    if err != nil {
        fmt.Println(err)
        return
    }
    run_curl := exec.Command("curl", "localhost:8500/v1/catalog/nodes")
    curl_out, err := run_curl.Output()
    if err != nil {
        fmt.Println(err)
        return
    }
    endtime := go ping(string(curl_out))
    container_id, err = exec.Command("docker", "stop", container_id)
    if err != nil {
        fmt.Println(err)
        return
    }
    startime := time.Now().Unix()
    fmt.Println("delay is", endtime-startime)
}

# command-line-arguments
./main.go:9: syntax error: unexpected name, expecting semicolon or newline
./main.go:11: non-declaration statement outside function body
./main.go:15: non-declaration statement outside function body
./main.go:16: non-declaration statement outside function body
./main.go:17: non-declaration statement outside function body
./main.go:18: syntax error: unexpected }

此代码计算泊坞窗启动和停止之间的时间。 我使用例程来返回结束时间。

endtime := go ping(string(curl_out))

我认为这是错误的。我怎样才能使用关键字go?

在Go中,我是否在函数体外减速语句?

2 个答案:

答案 0 :(得分:3)

有两个主要问题(和许多不相关的问题)。

首先,您需要为命名的返回参数括号

func ping(curl_out string) (endtime int64) {

其次,您无法指定goroutine的返回值。它在一个全新的上下文中异步执行。使用频道在goroutine之间进行通信

您可以将ping函数声明为:

func ping(curl_out string, endtime chan<- int64) {

然后传入要接收值的频道

ch := make(chan int64)
go ping(string(curl_out), ch)
endtime <- ch

(虽然在这种情况下没有必要使用goroutine,因为你想同步这个值)

答案 1 :(得分:1)

第9行:

添加括号

func ping(curl_out string) (endtime int64) {

或删除返回值名称:

func ping(curl_out string) int64 {

您使用go关键字创建goroutine是正确的,您不能将其分配给返回值,只需删除go关键字并直接指定值。 / p>

此外,(样式)go变量位于camelCase中,因此您应该将变量从run_container更改为runContainer或更好container或更好c,同样适用于run_curl,可能是curl

这是代码的略微增强版本(不知道它的作用)

http://play.golang.org/p/3Y7TPip5kP

相关问题