Go 语言指针运算符 ``& ``和 ``*`` 使用教程


发布日期 : 2021-10-02 23:13:45 UTC

访问量: 10 次浏览

Go 其他运算符

Go语言还支持一些其他重要的运算符,包括 &*

注意:Go语言没有三元运算符 ?:,也没有 sizeof 运算符。sizeof 功能由 unsafe.Sizeof() 函数提供。

运算符描述示例
&返回变量的地址。&a 提供变量的实际地址。
*指向变量的指针。*a 提供指向变量的指针。

示例

尝试以下示例,以理解Go编程语言中提供的所有其他运算符。

package main

import "fmt"

func main() {
   var a int = 4
   var b int32
   var c float32
   var ptr *int

   /* example of type operator */
   fmt.Printf("Line 1 - Type of variable a = %T\n", a );
   fmt.Printf("Line 2 - Type of variable b = %T\n", b );
   fmt.Printf("Line 3 - Type of variable c= %T\n", c );

   /* example of & and * operators */
   ptr = &a /* 'ptr' now contains the address of 'a'*/
   fmt.Printf("value of a is  %d\n", a);
   fmt.Printf("*ptr is %d.\n", *ptr);
}

当您编译并执行上述程序时,将会产生以下结果 –

Line 1 - Type of variable a = int
Line 2 - Type of variable b = int32
Line 3 - Type of variable c= float32
value of a is  4
*ptr is 4.