Home  >  Article  >  Backend Development  >  When to use pointers in golang

When to use pointers in golang

(*-*)浩
(*-*)浩Original
2019-12-27 11:25:104648browse

When to use pointers in golang

#Sometimes when I look at other people's Go code, I find that some of them use pointers in the code, and some don't.

Suppose there is a structure type called Person, and it is found that some methods use func methodA (*person Person) as a parameter, or use func *(person Person) methodA() as the structure's own method , that is, the structure of person (recommended learning: go)

You can call methodA directly, but use a pointer.

Or you can see the usage of var personMap map[string]*Person in the map structure

If you transfer from java to golang, it may not be easy to understand. Because there are no pointers in the Java world, you can just pass it directly and use it. However, you need to pay attention to many things when going to golang.

So when should you use it? Why is it needed in some places?

If you don’t use pointers, you cannot assign values ​​to the structure in some cases.

Let’s look at a piece of code. This code does not use any pointers. , first define a bunch of objects for testing

type Person struct {  //person结构体,包含年龄,名称,车
    age  int
    name string
    car  Car
}

type Car struct {  //person名下的车
    name string  //车的名字
}

var personMap map[string]Person   //一个存放person的map

func setName(person Person, name string) { //给参数person设置名字
    person.name = name
}

func (person Person) setName(name string) {  //设置名字
    person.name = name
}
func printName(person Person){  //打印person的名字
    fmt.Println(person.name)
}
func (person Person)printName(){  //结构体person自己支持打印名字
    fmt.Println(person.name)
}

So we can conclude that when we need to modify the variable content of the structure, the structure variable parameters passed in by the method need to be used Pointer, that is, the address of the structure

When you need to modify the variables of the architecture in the map, you also need to use the structure address as the value of the map

If you just read the structure variable, you can pass the reference directly without using a pointer.

*type The type variable here stores the address. This needs to be clear. You need to use &type to get the address.

The above is the detailed content of When to use pointers in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn