dongyanzhui0524 2013-03-15 13:43
浏览 70
已采纳

如何阅读Go文档?

I've created a simple go program (basically just example code):

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
)

func getPage(url string) (body []byte, err error) {
    resp, err := http.Get(url)

    body = nil

    if (err != nil) {
        return
    }

    defer resp.Body.Close()
    body, err = ioutil.ReadAll(resp.Body)

    return
}

func main() {
    startUrl := "http://slashdot.org/"

    body, err := getPage(startUrl)

    if (err != nil) {
        fmt.Println("Error: " , err)
    }

    fmt.Println(body)
}

I'm trying to go through the docs to understand how it all fits together.

First issue: http.Get(). It's not in the docs (at http://golang.org/pkg/net/http/). Except it is, but under Response. However there are 2 other Get() functions. How do I know that net/http.Get is actually the Get() on the Response type?

Anyway, so http.Get() returns a Response with a Body of io.ReadCloser. ioutil.ReadAll() takes an io.Reader - but how can I find other functions that accept this as a parameter? It kind of seems like the docs are 'backwards' - if I know which function I want I can find docs, but if I have a type, how can I find what functions will work with it?

  • 写回答

2条回答 默认 最新

  • douqian8238 2013-03-15 13:48
    关注

    The functions are defined like this :

    func (c *Client) Get(url string) (resp *Response, err error)
    func (h Header) Get(key string) string
    func Get(url string) (resp *Response, err error)
    

    See how functions are declared.

    Between func and the name of the function (Get), you have the receiver type and name (between parenthesis). Only one of those functions has no receiver and must be called directly prefixed by the package name (http). That's the one you need.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)