dshgdhdfcas30210 2014-07-26 17:03
浏览 30
已采纳

新切片的第一个值为nil

I'm trying to create a simple proof-of-concept for an image resizing server in Golang. I'm new to golang, and am stuck at this frustrating issue. Maybe I haven't understood slices correctly, so please let me where I am wrong in the usage of slices.

I use request.ParseMultipartForm() to parse the files and any POST params sent to the server. Then, I need to convert the list of files (which are a map[string][]*multipart.FileHeader). I'm using the following code to do so.

    // convert the FileHeader map to a list of io.Readers
    images := make([]io.Reader, len(reqForm.File))
    fmt.Println(images)
    for _, fileHeaders := range reqForm.File {
        fh := fileHeaders[0]
        f, err := fh.Open()
        fmt.Printf("Converting: %v
", f)
        if err != nil {
            writeErrorToResponse(resp, err)
            return
        }

        images = append(images, f)
    }

My problem is, for some reason images ends up having a nil as it's first value after being initialized by make. I know this because the fmt.Println(images) (line of code 2) prints out:

[<nil>]

I assumed that the make would return a slice with zero elements. If I do a make([]io.Reader, 0) instead, it works as I expect. I'm confused with this behavior and an explanation would be very helpful.

  • 写回答

2条回答 默认 最新

  • dpglo66848 2014-07-26 17:17
    关注

    images := make([]io.Reader, len(reqForm.File)) creates a slice of the given length and the same capacity. When you later append to it, new values are put on the end.

    You can fix this in two ways:

    • start with a length 0, but the given capacity with images := make([]io.Reader, 0, len(reqForm.File))
    • start with an empty slice, and allow append to grow it naturally. var images []io.Reader.

    I'd choose the latter since it's slightly simpler, and replace it with the preallocated slice later if it turns out it's a bottleneck.

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

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改