You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言如何赋值自定义类型指针?代码验证与优化方案

Go类型转换:Source到Target的赋值实现

你给出的代码正确性分析

你提供的代码:

var target Target
var source Source

target.Value = new(MyType)
*target.Value = MyType(*source.Value)

仅在source.Value不为nil时能正常运行。如果source.Value是nil,直接解引用*source.Value会触发空指针panic,存在安全隐患。

更优的实现方式

1. 安全处理空指针的常规写法

先判断source.Value是否为空,再完成赋值,避免panic:

var target Target
var source Source

if source.Value != nil {
    mt := MyType(*source.Value)
    target.Value = &mt
} else {
    target.Value = nil // 保持与source一致的空值状态
}

2. 最简洁高效的写法

由于MyType是string的类型别名,*MyType和*string底层结构完全一致,可以直接进行指针类型转换,同时自动处理空指针情况:

var target Target
var source Source

target.Value = (*MyType)(source.Value)

这种写法既不需要额外的内存分配(比如new(MyType)会创建一个零值MyType实例),又能在source.Value为nil时,让target.Value也保持nil,完全规避空指针风险。

内容的提问来源于stack exchange,提问作者user826955

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 05:23:13