指向指针的最佳指针是什么? [英] What are pointers to pointers good for?

查看:75
本文介绍了指向指针的最佳指针是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Go编程语言;指向指针的指针如何变得有用?

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

(如果它们没有真正的用处,为什么不违法?)

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

推荐答案

任何数据类型的有效性都取决于要解决的问题和用于解决该问题的方法.如果数据类型不适合该问题,那么它根本就不适合该问题-别无所求.

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.

Go编程语言(以及大多数其他编程语言)基于简单规则,程序员可以使用这些规则来构建新的数据类型.其中一些规则是:

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:创建一个新数据类型,该数据类型是指向T的指针
  • [10]T:一个Ts数组
  • struct { t T; u U ... }:包含T作为成分的结构
  • ...
  • *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.

类型**T属于不太可能出现在程序中的类型类别.可以编写*****T的事实并不意味着这种类型必须非常有用.

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.

最后,是您问题的答案:

类型**T通常出现在我们想要将类型为T的用户重定向到类型为T的另一个值的上下文中,但是由于某些原因,我们无法访问该值的所有用户否则找到用户会花费太多时间:

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. 我们不想复制T类型的值(出于某种原因)
  2. 我们希望所有类型为T的用户都可以通过指针访问该值
  3. 我们想迅速T类型的特定值的所有用户重定向到另一个值
  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

在这种情况下,使用**T是很自然的,因为它允许我们在O(1)中实现第三步:

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
}

这篇关于指向指针的最佳指针是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆