dstm2014 2016-06-07 09:47
浏览 37
已采纳

Golang:脚本中的go命令?

I got a script written in Golang that I do not quite understand. I want to know why he wrote go server.Start() inside the script? Why not simply write server.Start?

package main

import (
    "github.com/miekg/dns"
    "testing"
    "time"
)

const TEST_ADDR = "127.0.0.1:9953"

func TestDNSResponse(t *testing.T) {
    server := NewDNSServer(&Config{
        dnsAddr: TEST_ADDR,
    })
    go server.Start()

    // Allow some time for server to start
    time.Sleep(150 * time.Millisecond)

    m := new(dns.Msg)
    m.Id = dns.Id()
    m.Question = []dns.Question{
        dns.Question{"docker.", dns.TypeA, dns.ClassINET},
    }
    c := new(dns.Client)
    _, _, err := c.Exchange(m, TEST_ADDR)

    if err != nil {
        t.Error("Error response from the server", err)
    }

    server.Stop()

    c = new(dns.Client)
    _, _, err = c.Exchange(m, TEST_ADDR)

    if err == nil {
        t.Error("Server still running but should be shut down.")
    }
}
  • 写回答

1条回答 默认 最新

  • dongqing344716 2016-06-07 09:54
    关注

    If you invoke a function prefixed with the go keyword it will call the function in as goroutine. A goroutine is a function that is capable of running concurrently with other functions.

    Normally when we invoke a function it will execute all the function statements in normal order, then return to the next line following the invocation. With a goroutine we return immediately to the next line and don't wait for the function to complete.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏