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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度