Which init Func do you prefer?

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)
}

Hello,
I would like to use double pointers if I don’t have a chance to check and initialize p in the same block, like the following example:

package main

import "fmt"

type myStruct struct {
	a map[string]string
}

func main() {
	var p *myStruct
    
    // check and initialize p
	if p == nil {
		p = &myStruct{
			a: map[string]string{},
		}
	}

	if p == nil {
		fmt.Println("p is not initialized")
		return
	}
	if p.a == nil {
		fmt.Println("p.a is not initialized")
	}
	fmt.Println("p is initialized")
}

Why not just

func newMyStruct() *myStruct {
    return &myStruct{
        a: make(map[string]string),
    }
}
2 Likes

That’s a good way!
When I ask this question, I just want to ensure the initialize of the variable, the input is for that case: the variable has been initialized before execute this code session.
However, I found that this case can be avoided by reformat my code…