Go指针初始化

复制代码
var post *models.Post
res := postDao.SavePost(post)
复制代码
var post models.Post
res := postDao.SavePost(&post)

在1中将models.Pos声明为指针但是并没有为其分配内存空间,这意味着它的值为 nil,并且没有指向有效的 models.Post 对象。

复制代码
func Test1(t *testing.T) {
	var post *models.Post
	
	post.Id = 1
	fmt.Printf("%v", post)
}

这样访问就会出错:

复制代码
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
	panic: runtime error: invalid memory address or nil pointer dereference

第二种写法 var post models.Post 声明了一个直接的 models.Post 类型的变量,并为其分配了内存空间。然后,将 &post 作为参数传递给 SavePost 方法,将 post 变量的地址传递给了方法。

这样,SavePost 方法在使用 post 时可以访问到有效的内存空间,而不会导致内存错误。

如果想用第一种让post是一个指针变量并且有空间,应该这样写

复制代码
post := &models.Post{}
res := postDao.SavePost(post)

models.Post{}创建了一个新的对象,这个对象在内存空间,&将地址赋予给post,post成为指针

相关推荐
Reart3 分钟前
Leetcode 188.买卖股票的最佳时机4(718)
后端·算法
Reart19 分钟前
Leetcode 123.买卖股票的最佳时期3(内有随心谈,718)
后端·算法
只与明月听41 分钟前
LangChain 学习-掌握LangChain Core API
前端·人工智能·后端
nzz_1712141 小时前
PHP程序员转型AI岗位指南:核心技能、北京就业市场与转型路径分析
开发语言·人工智能·php
无相求码1 小时前
数组越界为什么有时候不崩溃?VS2013 下栈上变量的幽灵布局解密
c语言·后端
Risehuxyc1 小时前
C# 将doc转换为docx
开发语言·c#·xhtml
多加点辣也没关系2 小时前
JavaScript|第24章:事件循环与并发模型
开发语言·javascript·ecmascript
HONG````2 小时前
HarmonyOS ArkUI Image 组件完全指南:objectFit、占位图与加载回调
后端
ん贤2 小时前
怎么设计,才算一个优秀审计模块
大数据·开发语言·设计·审计
l1t2 小时前
测试用rust重写的postgresql: pgrust
开发语言·postgresql·rust