dqjgf0982 2016-04-24 18:49
浏览 20
已采纳

Golang的这一行到底做什么? 为什么要指针? 为什么使用0参数?

I was following this tutorial on PostgreSQL in Go and it has the following line:

  bks := make([]*Book, 0)

Which is part of the bigger code block:

  bks := make([]*Book, 0)
  for rows.Next() {
    bk := new(Book)
    err := rows.Scan(&bk.isbn, &bk.title, &bk.author, &bk.price)
    if err != nil {
      log.Fatal(err)
    }
    bks = append(bks, bk)
  }

Why does the author pass 0 in make? I understand that's the length, but why 0 length? And why is it an array of pointers instead of an array of books? Wouldn't you want a slice so you can insert books arbitrarily into it?

  • 写回答

1条回答 默认 最新

  • doulilou8560 2016-04-24 19:01
    关注

    Wouldn't you want a slice so you can insert books arbitrarily into it?

    make([]Type, initLength) creates a slice of values of type Type. When initLength > 0 then the slice is pre-filled with that many number of zero-value instances of type Type. In this case the author doesn't want to have any zero-values, and instead chooses to append non-zero values as they're received from the DB. So bks is indeed a slice.

    Example: http://play.golang.org/p/g0dALT-sLn

    More information: http://blog.golang.org/go-slices-usage-and-internals

    And why is it a slice of pointers instead of an slice of books?

    This is hard to answer without more context. Using a pointer to Book will allow you to store nil values, which might be useful depending on how bks is used.

    The tutorial you linked to doesn't show bks being used in any way that makes use of the fact the values are pointers. You could probably convert the slice to type []Book without any problems.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?