doutui8842 2017-01-10 01:59
浏览 34

为什么在此golang教程中将指针用于结构实例? [关闭]

Making a simple api in golang, why does this tutorial use

var movies = map[string]*Movie{
    "tt0076759": &Movie{Title: "Star Wars: A New Hope", Rating: "8.7", Year: "1977"},
    "tt0082971": &Movie{Title: "Indiana Jones: Raiders of the Lost Ark", Rating: "8.6", Year: "1981"},
}

while this other tutorial uses something more like:

type Movies []Movie
var movies Movies
movies = append(movies, Movie{id: "tt0076759", Title: "Star Wars: A New Hope", Rating: "8.7", Year: "1977"})

It seems like the first one gives me a map containing key value pairs where the value is a pointer to a movie. And the second one gives me an array(slice?) of movies where the id serves as the key for lookup. Why are pointers used in the first one?

  • 写回答

2条回答 默认 最新

  • doupijin0397 2017-01-10 04:24
    关注

    First of all you need to understand what pointer is used for. When you want to share the value use Pointer as the Tour of Go

    A pointer holds the memory address of a value

    As the first tutorial because they wanted to create variable that share value so it uses less memory.

    As the second tutorial you don't need to add pointer variable to a slice. Because Slice it self is a reference type.

    Slices hold references to an underlying array, and if you assign one slice to another, both refer to the same array.

    some reference : https://golang.org/doc/effective_go.html#slices
    https://stackoverflow.com/a/2441112/2652524

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算