Pointers Can';t正确地取消引用指针,并从内存地址数组中获取实际值

Pointers Can';t正确地取消引用指针,并从内存地址数组中获取实际值,pointers,go,Pointers,Go,在过去的几天里,我开始选择Go,主要依靠语言规范和包文档,但是我在破译net.LookupNS的正确用法时遇到了问题。 由于它是指针类型,返回NS服务器值的内存地址数组,因此我希望访问实际值/取消对数组的引用 节目: package main import "fmt" import "net" import "os" var host string func args() { if len(os.Args) != 2 { fmt.Println("You need

在过去的几天里,我开始选择Go,主要依靠语言规范和包文档,但是我在破译net.LookupNS的正确用法时遇到了问题。 由于它是指针类型,返回NS服务器值的内存地址数组,因此我希望访问实际值/取消对数组的引用

节目:

package main

import "fmt"
import "net"
import "os"

var host string

func args() {
    if len(os.Args) != 2 {
        fmt.Println("You need to enter a host!")
    } else {
        host = os.Args[1]
    }
    if host == "" {
        os.Exit(0)
    }
}

func nslookup() []*net.NS {
    nserv, err := net.LookupNS(host)
    if err != nil {
        fmt.Println("Error occured during NS lookup", err)
    }
    return *&nserv
}

func main() {
    args()
    fmt.Println("Nameserver information:", host)
    fmt.Println("   NS records:", nslookup())
}
例如google.com,它会显示以下内容:

Nameserver information: google.com
   NS records: [0xc2100376f0 0xc210037700 0xc210037710 0xc210037720]
Nameserver information: google.com
   NS records: &{ns1.google.com.} 
我希望看到的不是内存地址位置,而是解引用的值,例如:

   NS records: ["ns1.google.com", "ns2.google.com", "ns3.google.com", "ns4.google.com"]
现在很明显,我更喜欢将它们作为字符串的数组/片段,但问题是,我可以获得实际名称服务器的唯一方法如下:

func nslookup() *net.NS {
  // The rest of the function
return *&nserv[0] // This returns the first nameserver
上面返回的结果如下:

Nameserver information: google.com
   NS records: [0xc2100376f0 0xc210037700 0xc210037710 0xc210037720]
Nameserver information: google.com
   NS records: &{ns1.google.com.} 
虽然这至少返回实际值而不是内存地址,但它需要索引,这不是很灵活,也不是以非常用户友好的格式进行格式化。 此外,无法将[]*net.NS结构直接转换为字符串

问题: 如何获取名称服务器数组,而不是内存地址,最好是作为字符串的数组/片段?

确定一些问题:

  • 为什么要返回
    *&nserv
    ?围棋不是C,请停止你正在做的一切并阅读

  • 您的
    nslookup
    函数返回一片
    *net.NS
    ,这是一片指针,因此
    fmt.Println
    是正确的打印方式,如果您需要更多细节,可以使用
    %\v
    %\q
    修饰符查看数据的实际外观

例如:

package main

import "fmt"
import "net"
import "os"

var host string

func nslookupString(nserv []*net.NS) (hosts []string) {
    hosts = make([]string, len(nserv))
    for i, host := range nserv {
        hosts[i] = host.Host
    }
    return
}

func nslookupNS(host string) []*net.NS {
    nserv, err := net.LookupNS(host)
    if err != nil {
        fmt.Println("Error occured during NS lookup", err)
    }
    return nserv
}

func init() { //initilizing global arguments is usually done in init()
    if len(os.Args) == 2 {
        host = os.Args[1]
    }
}

func main() {
    if host == "" {
        fmt.Println("You need to enter a host!")
        os.Exit(1)
    }
    fmt.Println("Nameserver information:", host)
    ns := nslookupNS(host)
    fmt.Printf("   NS records String: %#q\n", nslookupString(ns))
    fmt.Printf("   NS records net.NS: %q\n", ns)
    for _, h := range ns {
        fmt.Printf("%#v\n", h)
    }

}

回答得很好,正是我想要的。