Golang assigns values to the properties of the pointer type of the underlying data type of the object

overview

Sometimes we may come across a structure defined as follows, some attributes in the structure are basic data types, more precisely, pointer types of basic data types.

type Student struct {
	name string `json:"name"`
	age  *int   `json:"age"` // age 是整型指针
}

Impossible to write

How to assign a value to this member attribute at this time, the following two ways of writing are wrong, and the syntax check of the compiler will report an error.

Impossible way to write one:

stu := Student{
		name: "zhangsan",
		age: &1, // 提示:Cannot take the address of '1'
	}

Impossible way of writing two:

stu := Student{
		name: "zhangsan",
		age: &int(1), // 提示:Cannot take the address of 'int(1)'
	}

correct spelling

First define a variable corresponding to the basic data type, and then assign the address of the variable to the property of the object

temp := 1
	stu := Student{
		name: "zhangsan",
		age: &temp,
	}

Guess you like

Origin blog.csdn.net/qq_41767116/article/details/131346894