What are pointers to pointers good for?

后端 未结 5 1615
难免孤独
难免孤独 2021-02-04 10:01

In the Go programming language; how can pointers to pointers become useful?

(Why are they not illegal if they are not really useful?)

5条回答
  •  离开以前
    2021-02-04 10:41

    The usefulness of any data type depends on the problem being solved and on the method used to solve the problem. If a data type does not fit the problem, it simply does not fit the problem - and there is nothing more to it.

    The Go programming language (as well as most other programming languages) is based on simple rules that the programmer can use to build new data types. Some of these rules are:

    • *T: create a new data type that is a pointer to T
    • [10]T: an array of Ts
    • struct { t T; u U ... }: a structure which contains a T as a component
    • ...

    The programmer can create complex data types by composing these simple rules. The total number of possible data types exceeds the number of useful data types. Clearly, there exist (and have to exist) data types which aren't useful at all. This is just a natural consequence of the fact that the rules for building new data types are simple.

    The type **T falls into the category of types which are less probable to appear in a program. The fact that it is possible to write *****T doesn't imply that such a type has to be immensely useful.


    And finally, the answer to your question:

    The type **T usually appears in contexts where we want to redirect users of a value of type T to another value of type T, but for some reason we do not have access to all users of the value or finding the users would cost too much time:

    1. We do not want to copy values of type T (for some reason)
    2. We want all users of a value of type T to access the value via a pointer
    3. We want to quickly redirect all users of a particular value of type T to another value

    In such a situation, using **T is natural because it allows us to implement the 3rd step in O(1):

    type User_of_T struct {
      Value **T
    }
    
    // Redirect all users of a particular value of type T
    // to another value of type T.
    func (u *User_of_T) Redirect(t *T) {
      *(u.Value) = t
    }
    

提交回复
热议问题