在Golang中访问结构变量中字段的地址。

huangapple go评论102阅读模式
英文:

Access address of Field within Structure variable in Golang

问题

在Golang中,要访问结构体(STRUCTURE)中字段(FIELD)的指针或地址,你可以使用以下方法。假设你已经有了整个结构体变量的地址或指针。

首先,你可以使用.操作符来访问结构体中的字段。例如,如果你有一个指向结构体的指针ptr,你可以通过ptr.field来访问字段。

另外,你也可以使用(*ptr).field的方式来访问字段。这里的*ptr表示解引用指针,得到结构体变量,然后再通过.操作符来访问字段。

以下是一个示例代码:

  1. package main
  2. import "fmt"
  3. type MyStruct struct {
  4. Field int
  5. }
  6. func main() {
  7. var s MyStruct
  8. s.Field = 42
  9. ptr := &s
  10. // 通过`.`操作符访问字段
  11. fmt.Println(ptr.Field)
  12. // 通过解引用指针和`.`操作符访问字段
  13. fmt.Println((*ptr).Field)
  14. }

在上面的代码中,我们定义了一个名为MyStruct的结构体,其中包含一个整型字段Field。在main函数中,我们创建了一个结构体变量s,并将其地址赋值给指针ptr。然后,我们使用.操作符和解引用指针的方式来访问结构体中的字段,并打印出字段的值。

希望这可以帮助到你!如果你还有其他问题,请随时提问。

英文:

How to access the pointer or the address of a FIELD within a STRUCTURE in GOLANG. I have the address or pointer of the whole structure variable but can not properly access the address of the field inside structure. So far I have tried Reflection but seems breaking somewhere. Any help is highly appreciated.

答案1

得分: 4

例如,

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type S struct{ F1, F2 int }
  6. func main() {
  7. s := new(S)
  8. f1, f2 := &s.F1, &s.F2
  9. fmt.Printf("%p %p %p\n", s, f1, f2)
  10. }

输出:

  1. 0x1040a128 0x1040a128 0x1040a12c
英文:

For example,

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type S struct{ F1, F2 int }
  6. func main() {
  7. s := new(S)
  8. f1, f2 := &s.F1, &s.F2
  9. fmt.Printf("%p %p %p\n", s, f1, f2)
  10. }

Output:

  1. 0x1040a128 0x1040a128 0x1040a12c

huangapple
  • 本文由 发表于 2017年6月26日 10:35:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/44752447.html
匿名

发表评论

匿名网友

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

确定