当前位置:网站首页>pointer of go language

pointer of go language

2022-09-23 08:49:5851CTO

goThe pointer usescThe syntax of language pointers,我们需要特别关注&和*,&Represents an address operator,The memory address of the specified variable can be obtained.

      
      
abc : = 10
fmt . Println( & abc)
  • 1.
  • 2.

打印出来的是abc的地址,We can do this by prepending the variable*对其进行解引用

      
      
fmt . Println( * abc)
  • 1.

打印出来是10

Pointer types can be the same as other ordinary types,Appears wherever types are needed,如变量声明、函数形参、返回值类型、Structure field types, etc.

      
      
var abc * string
fmt . Printf( "abc is a %T\n", abc)
  • 1.
  • 2.

打印出abc is a string

So the basic usage of a pointer is to use a variable to point to an address,通过&prefix to represent the address,通过前缀*to dereference to get the value of a specific variable.

Prefixes are also available*to modify the specific value.

      
      
var tt * string
mn : = "abc"
tt = & mn
* tt = "tt"
fmt . Println( * tt)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

Pointers are often used with structures,If the structure is used as a parameter,Want to modify the value of the struct,Passing a pointer to a structure is a better approach

      
      
type Hero struct {
Name string
}
hero : = & Hero{
Name: "刘备"
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

在函数中使用hero.Name就可以修改Name的值.

跟结构体一样,We can also pass the address operator&Placed in front of an array compound literal to create a pointer to an array.

      
      
abc : = &[ 3] string{ "aaa", "bbb", "ccc"}
fmt . Println( abc[ 0])
  • 1.
  • 2.

Dereferencing can be automatically implemented directly by indexing,没必要写成(*abc)[0].

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://chowdera.com/2022/266/202209230841149019.html

随机推荐