golang 给对象的基础数据类型的指针类型的属性赋值

概要

有时我们可能碰到定义成下面这样的结构体,结构体里某些属性是基础数据类型,更确切的说,是基础数据类型的指针类型。

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

不可行的写法

此时该如何对这种成员属性进行赋值呢,下面两种写法是错误的,编译器的语法检查会报错。

不可行的写法一:

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

不可行的写法二:

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

正确写法

先定义一个对应基础数据类型的变量,然后把变量取地址赋值给对象的属性

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

猜你喜欢

转载自blog.csdn.net/qq_41767116/article/details/131346894