What does this line of Golang do exactly? Why pointers? Why the 0 param?

huangapple go评论110阅读模式
英文:

What does this line of Golang do exactly? Why pointers? Why the 0 param?

问题

我正在翻译你提供的内容,请稍等片刻。

我正在翻译的内容是关于在Go语言中使用PostgreSQL的教程中的一段代码。在这段代码中,作者使用了以下代码:

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

这是一个更大代码块的一部分:

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)
}

为什么作者在make函数中传入了0?我理解这是长度,但为什么是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

得分: 5

“你不想要一个切片,这样你就可以任意地将书插入其中吗?”
make([]Type, initLength) 创建了一个类型为 Type 的值的切片。当 initLength > 0 时,切片会预先填充指定数量的类型为 Type 的零值实例。在这种情况下,作者不想要任何零值,而是选择在从数据库接收到非零值时追加它们。所以 bks 确实是一个切片。

示例:http://play.golang.org/p/g0dALT-sLn

更多信息:http://blog.golang.org/go-slices-usage-and-internals

“为什么它是指针的切片,而不是书的切片?”
没有更多的上下文很难回答这个问题。使用 Book 的指针可以存储 nil 值,这可能取决于 bks 的使用方式是否有用。

你链接的教程没有展示 bks 在任何使用方式上利用值是指针的事实。你可能可以将切片转换为类型 []Book 而没有任何问题。

英文:

> 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.

huangapple
  • 本文由 发表于 2016年4月25日 02:49:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/36827439.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定