When is the pointer idiomatic?

I come from languages ​​that do not have explicit pointers, so I do not really understand the meaning of their existence (pun intended).

The problem is that I have no idea, most of the time, why I pass a pointer to a function. I really understand that when you pass a pointer, changes to a variable are made with the value everywhere, but what is the point? Why not just change the value and return the result?

For example, http.HandlerFunc- a function that takes http.ResponseWriterand *http.Requestas arguments. I read that interfaces are actually pointers (is that right?), But what I am not getting, why?

Why am I getting a pointer to the author? I do not change him, I just write to him. And why am I getting a request pointer? I do things like request.FormValue().

What I'm trying to define here through these examples is the answer to the question: "When do I need to pass a pointer?"

The way I am doing this now is to write my code, try to compile it, fix errors that say I should pass a pointer by adding an ampersand and an asterisk until the errors go away. However, I feel that this half-understood concept of pointers will soon bite me from behind.

+4
source share
3 answers

, . (, 8 ) .

, 8 , , .

Request ( , ) , .

+2

, , , .

, - . , , , (, , http.Request ), , , . net/http , , . (, Go , , - .)

, , , , , , . , , , . go, , , , .

+1

, , , , , C. , , ..

, , , , - .

. , , , .

, . .

, , PHP, , copy on write algorithm, , , , , .

. cost Go , , , . C, ++ .

http.ResponseWriter, - ( ), , , .., , - , , .

PHP Java , .

,

, Interface{} Go, , , . , : , , , , XML JSON. ! , - - , / .

But you can also use the term Interface to define an interface (e.g. java, C #, php, etc.) and use implementation methods. When any of the structures that satisfies these methods. It naturally implements the interface. This implementation project, called Duck Typing, is being read for more information https://en.wikipedia.org/wiki/Duck_typing

-1
source

Source: https://habr.com/ru/post/1625888/


All Articles