dqqt31923 2016-07-28 00:23
浏览 67
已采纳

Go中的'key,ok:= k。(* dns.A)'是什么意思?

I am pretty new to Go and trying to write a DNS server by using package miekg DNS. According its example, I copy & pasted a simple snippet to perform A record request:

package main

import "fmt"
import "github.com/miekg/dns"

func main() {
    config, _ := dns.ClientConfigFromFile("/etc/resolv.conf")
    c := new(dns.Client)
    m := new(dns.Msg)
    zone := "miek.nl"
    m.SetQuestion(dns.Fqdn(zone), dns.TypeA)
    m.SetEdns0(4096, true)
    r, _, err := c.Exchange(m, config.Servers[0]+":"+config.Port)
    if err != nil {
        return
    }
    if r.Rcode != dns.RcodeSuccess {
        return
    }
    _ = "breakpoint"
    for _, k := range r.Answer {
        if key, ok := k.(*dns.A); ok {
            fmt.Printf("%+v
", key)
        }
    }
}

Loading by godebug, stopped at _ = "breakpoint":

./godebug run ~/aRequest.go  -d /usr/local/go/
-> _ = "breakpoint"
(godebug) p r.Answer
[]dns.RR{(*dns.A)(0xc8200120c0)}
(godebug) n
-> for _, k := range r.Answer {
(godebug) n
-> if key, ok := k.(*dns.A); ok {
(godebug) p k
&dns.A{Hdr:dns.RR_Header{Name:"miek.nl.", Rrtype:0x1, Class:0x1, Ttl:0x708, Rdlength:0x4}, A:net.IP{0x8b, 0xa2, 0xc4, 0x4e}}
(godebug) n
-> fmt.Printf("%+v
", key)
(godebug) p key 
&dns.A{Hdr:dns.RR_Header{Name:"miek.nl.", Rrtype:0x1, Class:0x1, Ttl:0x708, Rdlength:0x4}, A:net.IP{0x8b, 0xa2, 0xc4, 0x4e}}
(godebug) p ok
true

According godebug, ok == true and key seemed same as k. How could k.(*dns.A) return two variables?

  • 写回答

1条回答 默认 最新

  • dougong5817 2016-07-28 00:29
    关注

    The expression k.(*dns.A) is a type assertion.

    The code asserts that k contains a *dns.A. The first return value is of type *dns.A. The second return value is a untyped bool indicating whether the assertion holds.

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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向