1: A pointer of struct is required to input and a same type pointer is returned int this init Func. (like ‘append’)
func initMyStruct_1(p *myStruct) *myStruct {
if p == nil {
p = &myStruct{}
}
if p.a == nil {
p.a = make(map[string]string)
}
return p
}
func main() {
var b *myStruct
b = initMyStruct_1(b)
}
2: A double pointer is required to input in this init Func.
func initMyStruct_2(p **myStruct) {
if p == nil {
// error process
}
if *p == nil {
*p = &myStruct{}
}
if (*p).a == nil {
(*p).a = make(map[string]string)
}
}
func main() {
var b *myStruct
initMyStruct_2(&b)
}
To build this two Funcs, I want to handle the situation that the input point is ‘nil’, if just pass the value like follows, then the pointer ‘b’ in Func main is still ‘nil’. Do you have better ways to solve this problem? Thanks!
func initMyStruct_3(p *myStruct) {
if p == nil {
p = &myStruct{}
}
if p.a == nil {
p.a = make(map[string]string)
}
return p
}
func main() {
var b *myStruct
initMyStruct_3(b)
}