'*'和'&'的含义是什么在Golang? [英] What is the meaning of '*' and '&' in Golang?
问题描述
我是Golang的新成员,并且正在执行 http://tour.golang.org/ 。任何人都可以解释我第1,3,5和7行这个函数,特别是'*'和'&'是做什么的?我的意思是通过在函数声明中提及它们,它们应该/期望做什么?一个玩具的例子:
1:func intial1(var1 int,var2 int,func1.newfunc [])* callproperfunction {
2:
3:addition:= make([] add1,var1)
4:for i:= 1; i< var2; i ++ {
5:var2 [i] = * addtother(randomstring(lengthofcurrent))
6:}
7:return& callproperfunction {var1 int,var2 int,func1.newfunc [],jackpot}
8:}
它们似乎是我们在C ++中所拥有的指针。但是我无法将这些概念与我们在这里的内容联系起来。换句话说,当我在Go中的函数声明中使用它们时,'*'和''会做什么。
编辑:我知道什么是参考和解除引用的意思。我无法理解的是:我们如何使用指向函数的指针是Golang。例如第1行和第7行,这两行代表什么?我们声明了一个名为intial1的函数,它返回一个指针?在第7行中,我们使用返回函数的参数来调用它。
这些指针就像我们在C ++中一样。
区别在于:
-
取代
- >
在一个指针上调用一个方法,你总是使用。
,即pointer.method() code>。
-
没有悬挂指针。返回指向局部变量的指针是完全有效的。 Golang将确保对象的生命周期,并在不再需要时对其进行垃圾回收。
使用
new )
或通过创建一个对象 object {}
并将其地址与&
。 Golang不允许指针算术(数组不会衰减指针)和不安全的转换。所有的downcasts都将使用变量的运行时类型和 panic
进行检查,或者在实例类型错误时返回false作为第二个返回值,具体取决于您是否实际上需要第二种返回类型。 I am new in Golang and I am doing the http://tour.golang.org/. Could anyone explain me lines 1,3,5 and 7 this function especially what '*' and '&' do? I mean by mentioning them in a function declaration, what they are supposed/expected to do? A toy example:
1: func intial1(var1 int, var2 int, func1.newfunc[]) *callproperfunction {
2:
3: addition:= make ([] add1, var1)
4: for i:=1;i<var2;i++ {
5: var2 [i] = *addtother (randomstring(lengthofcurrent))
6: }
7: return &callproperfunction {var1 int, var2 int, func1.newfunc[], jackpot}
8: }
It seems that they are pointers like what we have in C++. But I cannot connect those concepts to what we have here. In other words, what '*' an '&' do when I use them in function declaration in Go.
Edit: I know what reference and dereference mean. What I cannot understand is: how we can use pointer to a function is Golang. for example line 1 and 7, what these two line do? we declared a function named intial1 that return a pointer? and in line 7, we call it with arguments using return function.
Those are pointers like we have in C++.
The differences are:
Instead of
->
to call a method on a pointer, you always use.
, i.e.pointer.method()
.There are no dangling pointers. It is perfectly valid to return a pointer to a local variable. Golang will ensure the lifetime of the object and garbage-collect it when it's no longer needed.
Pointers can be created with
new()
or by creating a objectobject{}
and taking the address of it with&
.Golang does not allow pointer-arithmetic (arrays do not decay to pointers) and insecure casting. All downcasts will be checked using the runtime-type of the variable and either
panic
or return false as second return-value when the instance is of the wrong type, depending on whether you actually take the second return type or not.
这篇关于'*'和'&'的含义是什么在Golang?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!