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成为指针

相关推荐
Rain的Java大神之路13 分钟前
面了 50 个候选人,90% 都挂在 LeetCode 3 无重复字符的最长子串:滑动窗口的 5 个致命坑
java·后端·leetcode
qq_4017004120 分钟前
Qt Modbus 源码剖析:从 QModbusClient 到工业级通信框架
开发语言·qt·系统架构
星夜离尘5622 分钟前
MATLAB 角度解缠遇到丢样:先分段,再说明圈数为什么不可恢复
开发语言·matlab
我命由我1234530 分钟前
6-2.Python 异常处理 - 异常捕获(捕获指定异常、常见异常类型、异常信息)
java·运维·开发语言·python·http·https·java-ee
ZoeLandia33 分钟前
React08:自定义 Hook
开发语言·前端·react.js·typescript
狂师43 分钟前
夯爆了!分享几个我在用的,基于业务场景接口串联测试Skill !
人工智能·后端·测试
北京地铁1号线1 小时前
后端开发:缓存(Cache)简介
后端·缓存·cache
IT_陈寒1 小时前
Vue项目实战经验分享:动态组件在Keep-Alive下的缓存陷阱
前端·人工智能·后端
染指11101 小时前
157.Agent-LangGraph-工具(实现ReAct Agent模式)
开发语言·人工智能·python·langchain·agents
程序猿乐锅1 小时前
【从0-1学习Python | 第九篇】继承
开发语言·后端·python·学习·fastapi