Thus far in Go, it is said that we create variables inside a struct using data types such as int and string.
e.g
type Circle struct {
x int
y int
radius float64
area float64
}
But while building an API development project, pointers like *mux.Router and *sql.DB are used to declare the data type of variables inside the struct. Is it possible to define a variable using pointers? I don’t really get the concept behind this.
Here is a screenshot of the lecture on project setup.
The App
struct contains 2 pointer members call Router
and DB
The Router
member is a pointer to a mux.Router
etc.
The assignments at lines 18 and 23 re fine, because the first one returns a *sql.DB
and the second one a *mux.Router
There are pointers to DB
and Router
structs created within their packages.
You are more likely to want to interact with pointers to structs when
- The actual struct is large and passing it by value is inefficient
- There are methods associated with the structs that change its internal state - i.e. pointer receivers.
You should review the lessons on pointers.