apxp
apxp

Reputation: 5894

Initialize a variable over a function by reference in golang

If I have a function which takes a reference as an argument and I want to use that function to initialize a variable I need to do this inside the init() function. That solution works, but it smells not really correct to me.

Is there another way to initialize a variable for a package in go like to use the init() function?

I think that there must be a better way. I thought already about a wrapping function, but that makes the logik not better.

I prepared a short and simple example package main

import (
    "fmt"
)

var a string
//A use of a function is not allowed
//foo(&a)


//Need to call init
func init() {
    foo(&a)
}

func main() {
    fmt.Println(a)
}

func foo(b *string) {
    *b = "abc"
}

https://play.golang.org/p/GdBiDFB1KAe

Upvotes: 0

Views: 3810

Answers (1)

OneOfOne
OneOfOne

Reputation: 99224

That's fine, or you can just make a pointer and assign it like this:

var a = make("abc")

func main() {
    fmt.Println(*a)
}

func make(s string) *string {
    return &s
}

playground

Upvotes: 1

Related Questions