Golang如何使用结构体指针?代码示例

2021年3月30日10:11:25 发表评论 598 次浏览

指针Golang中是一个变量, 用于存储另一个变量的内存地址。 Golang中的指针也称为特殊变量。变量用于在系统中的特定内存地址存储一些数据。

你也可以使用指向结构。 Golang中的struct是用户定义的类型, 它允许将可能不同类型的项目分组/组合为单个类型。要使用指向结构的指针, 可以使用&运算符, 即地址运算符。 Golang允许程序员使用指针访问结构的字段, 而无需显式地取消引用。

示例1:在这里, 我们正在创建一个名为Employee的结构, 它具有两个变量。在main函数中, 创建struct的实例, 即emp。之后, 你可以将结构的地址传递给表示结构概念指针的指针。无需显式使用解引用, 因为它将产生与在以下程序中看到的结果相同的结果(两次ABC)。

// Golang program to illustrate the
// concept of the Pointer to struct
package main
  
import "fmt"
  
// taking a structure
type Employee struct {
  
     // taking variables
     name  string
     empid int
}
  
// Main Function
func main() {
  
     // creating the instance of the
     // Employee struct type
     emp := Employee{ "ABC" , 19078}
  
     // Here, it is the pointer to the struct
     pts := &emp
  
     fmt.Println(pts)
  
     // accessing the struct fields(liem employee's name)
     // using a pointer but here we are not using
     // dereferencing explicitly
     fmt.Println(pts.name)
  
     // same as above by explicitly using
     // dereferencing concept
     // means the result will be the same
     fmt.Println((*pts).name)
  
}

输出如下:

&{ABC 19078}
ABC
ABC

示例2:你还可以使用指针修改结构成员或结构文字的值, 如下所示:

// Golang program to illustrate the
// concept of the Pointer to struct
package main
  
import "fmt"
  
// taking a structure
type Employee struct {
  
     // taking variables
     name  string
     empid int
}
  
// Main Function
func main() {
  
     // creating the instance of the
     // Employee struct type
     emp := Employee{ "ABC" , 19078}
  
     // Here, it is the pointer to the struct
     pts := &emp
  
     // displaying the values
     fmt.Println(pts)
  
     // updating the value of name
     pts.name = "XYZ"
  
     fmt.Println(pts)
  
}

输出如下:

&{ABC 19078}
&{XYZ 19078}

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: