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 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题