The difference between * and & in Go language

The difference between * and & in Go language


  1. to sum up
  2. Example

I'm always confused about the difference between * and &, so today I deliberately summarized it.


1. Summary

  1. & Is the address character.
  2. * It can indicate that a variable is a pointer type, or it can indicate the storage unit pointed to by the pointer type variable, that is, the value pointed to by this address.

2. Example

  1. Code
type Person struct {
    
    
	name string
	age int
}

func main() {
    
    
	// & 是取地址符,取到Person类型对象的地址
	// 声明一个Person类型的结构体
	Bob := Person{
    
    "Bob", 20}
	fmt.Println("Bob:", Bob, " &Bob:", &Bob)

	// 声明一个Person类型的指针
	Lisa := &Person{
    
    "Lisa",30}
	fmt.Println("Lisa:",Lisa,"&Lisa:",&Lisa)

	// * 可以表达一个变量是指针类型
	var John *Person = &Person{
    
    
		name: "John",
		age:  40,
	}
	fmt.Println("John:",John," &John:",&John)

	// * 也可以表示指针类型变量所指向的存储单元,也就是这个地址所指向的值
	fmt.Println("*John:",*John)

	//函数参数是指针的话,会修改原来的数据
	changName(John)
	fmt.Println("*John:",*John)
}

func changName(p *Person) {
    
    
	// p 是一个指针
	//如果是基本数据类型 [p.name = "China"] == [(*p).name = "China"]
	//其他类型则必须用 * 取值
	(*p).name = "China"
	p.age = 100
}
  1. Output result
    Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_41910694/article/details/107917518