go - *[]Type 和 []*Type 在 go 中有什么区别

标签 go

假设我们有一个名为 Person 的结构,它由一个名为 People 的结构持有。

type Person {
    Name string
    age  int
}

type People {
    City string
    List []*Person //check this out
}

type People2 {
    City string
    List *[]Person //What's the difference?
}
  1. []*Person*[]Person到底是什么意思?

  2. 如何获取这些 slice 的元素值?

我比较熟悉 C,所以如果你能用 C 解释一下,我将不胜感激

最佳答案

  • []*Type 是指向 Type 的指针片段。
  • *[]Type 是指向 Type slice 的指针。

从指针 slice 中引用单个元素:

var x []*Type
y := *x[0]

从指向 slice 的指针中解引用单个元素:

var x *[]Type
y := (*x)[0]

为了加分,将单个元素从指针推导到指针 slice :

var x *[]*Type
y := *(*x)[0]

参见 playground .

关于go - *[]Type 和 []*Type 在 go 中有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50201366/

上一篇:Golang安装

下一篇:Golang IPv6 服务器

相关文章:

go - io.LimitReader 读取 http.Body 时的 EOF

go - 在 go 中使用接口(interface)进行依赖注入(inject)

reflection - 使用嵌入进行反射

Golang 上下文。上下文传播

windows - 使用 golang 创建硬链接(hard link)

go - 我无法将包从另一个目录导入到 main.go

go - 在 go 中迭代 2D slice

mongodb - 如何通过golang中的mgo在mongo中插入math/big.Int

nginx - 无法使用 NginX/FastCGI 建立 Websocket 连接

postgresql - 如何在go中模拟sql更新