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?
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
I glanced through the article and I can't see any particular reason. Perhaps he's implemented something that wasn't covered in that post like a method receiver for *Movie.
Consider this example: https://play.golang.org/p/SZb47MKIr3
It'll fail to compile because the "Print" function has a Pointer Receiver, but the instances in the map are not pointers.
Whereas this example: https://play.golang.org/p/g0aXXcze5d Runs fine.
This is a good post explaining the difference: https://nathanleclaire.com/blog/2014/08/09/dont-get-bitten-by-pointer-vs-non-pointer-method-receivers-in-golang/